你好,游客 登录 注册 搜索
背景:
阅读新闻

Objective-C语法property详解

[日期:2012-07-20] 来源:Linux社区  作者:totogo2010 [字体:大 中 小]

4、使用三种参数的对比

@property (nonatomic,retain)NSObject *obj;

@property (nonatomic,retain,readwrite) NSObject *obj;

readwrite是默认行为,所以这两行代码等价

@property (retain) NSObject *obj;

@property (atomic,retain) NSObject *obj;atomic是默认行为,所以这两行代码是等价的。

@property(atomic,assign)int number;       

@property(atomic) int number;       

@property int number; 

对int 来说,atomic assign都是默认行为,所以这三行是等价的。

@property  NSObject *obj;这样写行吗?不行的,报警告

只有int 等基础数据类型能这么写。对象必须加上赋值的类型。

@property  (retain) NSObject *obj;这样就没问题了。何时使用assign、何时使用retain、copy后面再讲。

5、retain和copy实验。

使用copy。

.h文件

  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface ViewController : UIViewController  
  4. {  
  5.     NSString *string;  
  6. }  
  7. @property  (nonatomic, copy) NSString *string;  
  8. @end  

.m文件

  1. @synthesize string;  
  2. - (void)viewDidLoad  
  3. {  
  4.     [super viewDidLoad];  
  5.       
  6.     NSString *str = [[NSString alloc] initWithFormat:@"abcd"];  
  7.     NSLog(@"str_Point:%p  %@  retainCount:%d", str, str, [str retainCount]);  
  8.     self.string = str;  
  9.     NSLog(@"string_Point:%p  %@  retainCount:%d", string, string, [string retainCount]);  
  10. }  

打印结果

2012-07-19 20:41:44.853 TestProject1[1213:f803] str_Point:0x6a8e0b0  abcd  retainCount:1

2012-07-19 20:41:44.854 TestProject1[1213:f803] string_Point:0x6a8e0b0  abcd  retainCount:2

内存地址是一样的,不是想其他文字所写的那样,拷贝了一份内存,这里用copy也是浅拷贝。retain也+1

使用retain

  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface ViewController : UIViewController  
  4. {  
  5.     NSString *string;  
  6. }  
  7. @property  (nonatomic, retain) NSString *string;  
  8. @end  

打印结果是:

2012-07-19 20:42:08.113 TestProject1[1230:f803] str_Point:0x6d3b8f0  abcd  retainCount:1

2012-07-19 20:42:08.114 TestProject1[1230:f803] string_Point:0x6d3b8f0  abcd  retainCount:2,

结果和上面copy一样。

注意:在IOS5之后,加入了Automatic Reference Counting (ARC),iOS5中新加了关键字有strong, weak, unsafe_unretained。

linux
相关资讯       Objective-C 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款