您的位置:首页 > 移动开发 > IOS开发

比较iOS类别Category和扩展Extension以及runtime的associative(关联)机制(容我水一发)

2015-01-21 14:33 627 查看
目前网上有很多介绍类别与扩展的文章,我这里就不班门弄斧了。我主要总结了一下他们之间的区别与联系。

Category与Extension在代码上的区别如下:

Category声明如下
@interface Demo (Category)

@end
Extension声明如下
@interface Demo ()

@end
Extension就像是匿名的类别,()里面没有内容。另外,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: