ios学习交流iOS面试那些事iOS技术中心

IOS下Category添加属性字段

2015-08-12  本文已影响7846人  zuolingfeng

首先说明一下,直接在Category中是不能添加属性的,就算在.m文件中实现了相应的getter和setter方法,调用的时候也是会报错的。

首先看下报错情况

Category添加字段(常规方法)

1, 编写Category头文件,以UIImage为例


//
//  UIImage+category.h
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//
#import <UIKit/UIKit.h>

@interface UIImage (category)

// 在UIImage中新建一个tag属性
@property (nonatomic, copy) NSString *tag;

@end

2,编写Category源文件

//
//  UIImage+category.m
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//

#import "UIImage+category.h"

@implementation UIImage (category)

- (NSString *)tag {
    return self.tag;
}

- (void)setTag:(NSString *)tag {
    self.tag = tag;
}
@end

3, 访问Category添加的tag属性

UIImage *image = [UIImage imageNamed:@""];
[image setTag:@"100"];
NSLog(@"tag:%@", [image tag]);

打印信息为:

2015-08-12 15:17:10.321 InformPub[16828:1373803] CUICatalog: Invalid asset name supplied: 
2015-08-12 15:17:10.321 InformPub[16828:1373803] tag:(null)

看到了没有,我们设置了tag值,完全没有用。那么有没有什么办法可以给Category添加属性字段呢?请看下面:

Category添加字段(Runtime方法)

1,编写Category头文件,还是以UIImage为例


//
//  UIImage+category.h
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//
#import <UIKit/UIKit.h>

@interface UIImage (category)

// 在UIImage中新建一个tag属性
@property (nonatomic, copy) NSString *tag;

@end

2,编写Category源文件

//
//  UIImage+category.m
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//

#import "UIImage+category.h"

static const void *tagKey = &tagKey;

@implementation UIImage (category)

- (NSString *)tag {
    return objc_getAssociatedObject(self, tagKey);
}

- (void)setTag:(NSString *)tag {
    objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end

3, 访问Category添加的tag属性

UIImage *image = [UIImage imageNamed:@""];
[image setTag:@"100"];
NSLog(@"tag:%@", [image tag]);

打印信息为:

2015-08-12 14:57:58.777 InformPub[16741:1271788] tag:100

到这里代码就添加完成了,Category就可以添加属性字段了。这里面用到了objective-c的Runtime。如果有不了解Runtime的小伙伴,可以参考以下网站:http://southpeak.github.io/blog/2014/10/25/objective-c-runtime-yun-xing-shi-zhi-lei-yu-dui-xiang/

上一篇下一篇

猜你喜欢

热点阅读