为Category添加属性


一般认为Category不能添加变量,其实可以使用@dynamic 来动态添加的。 (即运行时Runtime)
分类里面不能添加Ivar是因为分类本身并不是一个真正的类,它并没有自己的ISA。
原文出自http://blog.csdn.net/petyou123/article/details/51161522

1.创建UIViewController的类别并添加几个属性

#import <UIKit/UIKit.h>

@interface UIViewController (DefaultPage)

@property (nonatomic, strong) UIView *noMore_bgView;
@property (nonatomic, strong) UIImageView *noMore_showImg;
@property (nonatomic, strong) UILabel *noMore_showLab;

@end

2.UIViewController类别.m的实现 需要导入#import <objc/runtime.h>

#pragma mark --------------------  添加属性 ----------------------
#import "UIViewController+DefaultPage.h"
#import <objc/runtime.h>

@implementation UIViewController (DefaultPage)

static char *BgViewKey = "BgViewKey";
static char *ImgKey = "ImgKey";
static char *LabKey = "LabKey";

// 给noMore_bgView属性提供getter和setter方法
- (UIView *)noMore_bgView{
    return objc_getAssociatedObject(self, BgViewKey);
}
- (void)setNoMore_bgView:(UIView *)noMore_bgView{
    objc_setAssociatedObject(self, BgViewKey, noMore_bgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIImageView *)noMore_showImg{
    return objc_getAssociatedObject(self, ImgKey);

}
- (void)setNoMore_showImg:(UIImageView *)noMore_showImg{
    objc_setAssociatedObject(self, ImgKey, noMore_showImg, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}
- (UILabel *)noMore_showLab{
    return objc_getAssociatedObject(self, LabKey);
}
- (void)setNoMore_showLab:(UILabel *)noMore_showLab{
    objc_setAssociatedObject(self, LabKey, noMore_showLab, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容