详解Objective_C扩展机制学习
Objective_C扩展机制学习是本文要介绍的内容,学Objective_C已有一年时间了,开发iphone也有一年时间了。首先学习Objective_C的时候,是赁着c/c++的基础,所学的知识是按c/c++的方式去学习,其实Objective_C是 C 的超集当时一点也没体会到,其精髓也是完全没有理解到。随关时间的推移,慢慢了解更多。Objective_C比c/c++更强大,因为它包含了一些设计模式在里面。听说java里几乎包括了所有的设计模式,不过我没有深入用过java,曾经用过j2me写过一点点逻辑。用Objective_C最灵活的两 点就是:category与associative.我把他们归为Objective_C的扩展机制。category可以扩展一个类的方法,associative可以扩展一个类的属性。 这两种方法加起来其功能完全等效于c++中的继承。
下面看一个associative的列子,需要的头文件是:
[*]#import <objc/runtime.h>
[*]
[*]static char overviewKey = 'a';
[*]NSArray *array = [ initWithObjects:@ &quot;One&quot;, @&quot;Two&quot;, @&quot;Three&quot;, nil];
[*]// For the purposes of illustration, use initWithFormat: to ensure
[*]// we get a deallocatable string
[*]NSString *overview = [ initWithFormat:@&quot;%@&quot;, @&quot;First three numbers&quot;];
[*]objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
[*];
[*]NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
[*]NSLog(@&quot;associatedObject: %@&quot;, associatedObject);
[*]objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );
[*];
[*] static char overviewKey = 'a';
[*] NSArray *array = [ initWithObjects:@ &quot;One&quot;, @&quot;Two&quot;, @&quot;Three&quot;, nil];
[*] // For the purposes of illustration, use initWithFormat: to ensure
[*] // we get a deallocatable string
[*] NSString *overview = [ initWithFormat:@&quot;%@&quot;, @&quot;First three numbers&quot;];
[*] objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
[*] ;
[*] NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
[*] NSLog(@&quot;associatedObject: %@&quot;, associatedObject);
[*] objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );
[*] ;
objc_setAssociatedObject给array增加了一个属性,我们可以通过key获取这个属性,见上面代码:objc_getAssociatedObject, 第二个objc_setAssociatedObject设为nil,则是删除这个属性。
这儿还有一个例子:http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/关于category,大家就google一下吧。
小结:详解Objective_C扩展机制学习的内容介绍完了,希望通过本文的学习对你有所帮助!
【编辑推荐】
[*]关于Objective-C类声明相关学习文档
[*]简单学习iPhone重绘机制
[*]了解iPhone双缓冲机制内幕爆料
[*]Objective-C学习笔记相关教程
[*]Objective-C语法学习 初学者必备文档
[*]解析Objective-C程序设计
页:
[1]