比较iOS类别Category和扩展Extension以及runtime的associative(关联)机制(容我水一发)
2015-01-21 14:33
627 查看
目前网上有很多介绍类别与扩展的文章,我这里就不班门弄斧了。我主要总结了一下他们之间的区别与联系。
Category与Extension在代码上的区别如下:
Category声明如下
下面我们介绍一下associative(关联)机制来实现Category添加属性,我们可以这么写
这里有一篇博客,推荐大家可以下,是关于关联机制的,讲解的比较详细 http://blog.csdn.net/onlyou930/article/details/9299169
Category与Extension在代码上的区别如下:
Category声明如下
@interface Demo (Category) @endExtension声明如下
@interface Demo () @endExtension就像是匿名的类别,()里面没有内容。另外,Category一般只能添加方法,不能添加属性,为什么是一般呢,因为Category在借助associative(关联)机制的情况下是可以添加属性的,下文我们会说到。Category添加的方法不一定要实现。Extension不同,扩展既可以添加方法,也可以添加属性,但是扩展添加的方法必须要在.m文件中实现。
下面我们介绍一下associative(关联)机制来实现Category添加属性,我们可以这么写
<pre name="code" class="objc">// Declaration @interface MyObject (ExtendedProperties) @property (nonatomic, strong, readwrite) id myCustomProperty; @end // Implementation static void * MyObjectMyCustomPorpertyKey = (void *)@"MyObjectMyCustomPorpertyKey"; @implementation MyObject (ExtendedProperties) - (id)myCustomProperty { return objc_getAssociatedObject(self, MyObjectMyCustomPorpertyKey); } - (void)setMyCustomProperty:(id)myCustomProperty { objc_setAssociatedObject(self, MyObjectMyCustomPorpertyKey, myCustomProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end
这里有一篇博客,推荐大家可以下,是关于关联机制的,讲解的比较详细 http://blog.csdn.net/onlyou930/article/details/9299169
相关文章推荐
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS类别(Category)与扩展(Extension)
- iOS 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS扩展机制category与associative理解
- IOS中的类别(Category)和扩展(Extension)
- ios类别(Category)与扩展(Extension)
- iOS类别(Category)与扩展(Extension)
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS类别(Category)和扩展(Extension,匿名类)
- iOS学习系列 - 扩展机制category与associative
- iOS类别Category与扩展Extension
- iOS 扩展机制category与associative
- iOS类别(Category)与扩展(Extension,匿名类别)
- iOS类别(Category)与扩展(Extension)
- iOS学习系列 - 扩展机制category与associative