详解Objective_C扩展机制学习


  本文标签: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的列子,需要的头文件是:

  1. #import <objc/runtime.h> 
  2.  
  3. static char overviewKey = a;    
  4. NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];    
  5. // For the purposes of illustration, use initWithFormat: to ensure      
  6. // we get a deallocatable string      
  7. NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];    
  8. objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);     
  9. [overview release];    
  10. NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);    
  11. NSLog(@"associatedObject: %@", associatedObject);    
  12. objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );     
  13. [array release];    
  14.  static char overviewKey = a;  
  15.  NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];  
  16.  // For the purposes of illustration, use initWithFormat: to ensure   
  17.  // we get a deallocatable string   
  18.  NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];  
  19.  objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);   
  20.  [overview release];  
  21.  NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);  
  22.  NSLog(@"associatedObject: %@", associatedObject);  
  23.  objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );   
  24.  [array release]; 

  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扩展机制学习的内容介绍完了,希望通过本文的学习对你有所帮助!