iOS

为Category添加属性

2017-09-01  本文已影响0人  寻常_0

一般认为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

上一篇下一篇

猜你喜欢

热点阅读