美文网首页iOS开发
iOS - runtime 小技巧

iOS - runtime 小技巧

作者: WhoJun | 来源:发表于2015-09-06 16:15 被阅读234次

写category的时候,最纠结的就是想添加一个属性保存到对象中,却无从下手,这是最郁闷的事情。

那么我们可以用runtime来定义个属性保存到对象中。

//UILabel.h

@interface UILabel (WJ)

- (void)setMaxLine:(NSInteger)max;

- (NSInteger)maxLine;

@end

//UILabel.m

@implementation UILabel (WJ)

static void *kMaxLine = &kMaxLine;

- (void)setMaxLine:(NSInteger)max {

     objc_setAssociatedObject(self, kMaxLine, @(max), OBJC_ASSOCIATION_COPY);

}

- (NSInteger)maxLine {

     return [objc_getAssociatedObject(self, kMaxLine) integerValue];

}

@end

有些时候知道私有变量对象的名,缺想获取对应的私有变量对象,并修改他内部的属性。

//UINavigationBar.h

@interface UINavigationBar (WJ)

- (void)setProess:(CGFloat)proess;

- (CGFloat)proess;

@end

//UINavigationBar.m

@implementation UINavigationBar (WJ)

- (UIView *)wj_bgView {

     Ivar i = class_getInstanceVariable([self class],"_backgroundView");

     return object_getIvar(self, i);

}

- (void)setProess:(CGFloat)proess {

     self.wj_bgView.alpha = proess; 

}

- (CGFloat)proess {

     return self.wj_bgView.alpha;

}

@end

相关文章

网友评论

    本文标题:iOS - runtime 小技巧

    本文链接:https://www.haomeiwen.com/subject/dfkrcttx.html