iOS 进阶知识集

iOS - 关于动态绑定结构体属性

2016-06-23  本文已影响908人  Mitchell

写工程的时候遇到个问题,想要在 category 中添加一个结构体的属性,自然会想到使用 runtime 的动态绑定,但是添加结构体属性会与别的属性有些不同,有几个注意点:

#import <UIKit/UIKit.h>
@interface UIViewController (PushPopMessage)
@property (nonatomic)CGRect pushFrame;
@end
#import "UIViewController+PushPopMessage.h"
#import <objc/runtime.h>
@dynamic pushFrame;
@implementation UIViewController (PushPopMessage)
-(void)setPushFrame:(CGRect)pushFrame{
    NSValue *value = [NSValue value:&pushFrame withObjCType:@encode(CGRect)];
    //因为已经把 pushFrame 作为对象进行存储 所以也应该将存储的策略模式设置为对象的策略模式
    objc_setAssociatedObject(self, @"pushFrame", value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGRect)pushFrame{
    NSValue *value = objc_getAssociatedObject(self, @"pushFrame");
    if(value) {
        CGRect rect;
        [value getValue:&rect];
        return rect;
    }else {
        return CGRectZero;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读