OC-基于Runtime运用分类中增加属性

题记:在项目不紧张的闲暇时间研究研究提升自己的技术认知.

怎样实现分类增加属性?

在h文件中增加一个 page属性

@property (nonatomic, assign) NSInteger page;

在.m文件中 

对于一个属性而言其实就是实现了get和set方法,那么就应该从 get set方法入手,运用runtime机制动态添加关联属性

- (NSInteger)page{

return [objc_getAssociatedObject(self,@selector(page)) integerValue];

}

/**

* Returns the value associated with a given object for a given key.

*

* @param object The source object for the association.

* @param key The key for the association.

*

* @return The value associated with the key \e key for \e object.

*

* @see objc_setAssociatedObject

*/

objc_getAssociatedObject 这个方法实现的是根据给定对象的key值返回一个附加的值

- (void)setPage:(NSInteger)page{

    objc_setAssociatedObject(self,@selector(page),@(page),OBJC_ASSOCIATION_ASSIGN);

}

/**

* Sets an associated value for a given object using a given key and association policy.

*

* @param object The source object for the association.

* @param key The key for the association.

* @param value The value to associate with the key key for object. Pass nil to clear an existing association.

* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”

*

* @see objc_setAssociatedObject

* @see objc_removeAssociatedObjects

*/

objc_setAssociatedObject 这个方法实现的是填充给定对象的key和策略

为何需要在运行时增加属性而不是直接就在某个类中增加属性?

原理:在编译的时候类就已经完成了内存布局已经不能在动,而分类是在运行时加载,将属性的t方法拷贝到类的方法列表中但是属性没有拷贝.

这样做的好处有哪些呢?

我们都知道,iOS 编写的代码是先使用编译器把代码编译成机器码,然后直接在 CPU 上执行机器码的。之所以不使用解释器来运行代码,是因为苹果公司希望 iPhone 的执行效率更高、运行速度能达到最快。如果直接在类中添加一些比较复杂的控件例如tableview这样会极大消耗内存,一下子会让内存爆满这样就很浪费宝贵的内存空间.

总结:路漫漫其修远兮 吾将上下而求索.

发布了9 篇原创文章 · 获赞 0 · 访问量 307

猜你喜欢

转载自blog.csdn.net/Coding_Physical/article/details/104010762