一般認(rèn)為Category不能添加變量壶熏,其實(shí)可以使用@dynamic 來(lái)動(dòng)態(tài)添加的涌攻。 (即運(yùn)行時(shí)Runtime)
分類(lèi)里面不能添加Ivar是因?yàn)榉诸?lèi)本身并不是一個(gè)真正的類(lèi),它并沒(méi)有自己的ISA辙纬。
原文出自http://blog.csdn.net/petyou123/article/details/51161522
1.創(chuàng)建UIViewController的類(lèi)別并添加幾個(gè)屬性
#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類(lèi)別.m的實(shí)現(xiàn) 需要導(dǎo)入#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