随笔 - 22, 文章 - 0, 评论 - 0, 引用 - 0
数据加载中……

objective-c 中 @property中属性参数

Objective-C语言关键词,与@synthesize配对使用。

  功能:让编译好器自动编写一个与数据成员同名的方法声明来省去读写方法的声明。

  如:

  1、在头文件中:

  @propertyint count;

  等效于在头文件中声明2个方法:

  -(int)count;

  -(void)setCount:(int)newCount;

  2、实现文件(.m)中

  @synthesizecount;

  等效于在实现文件(.m)中实现2个方法。

  -(int)count

  {

  return count;

  }

  -(void)setCount:(int)newCount

  {

  count =newCount;

  }

  以上等效的函数部分由编译器自动帮开发者填充完成,简化了编码输入工作量。

 

 格式

 

声明property的语法为:

  @property(参数1,参数2)类型 名字;

  如:

  @property(nonatomic,retain)UIWindow *window;

  其中参数主要分为三类:

  读写属性: (readwrite/readonly)

  setter语意:(assign/retain/copy)

  原子性: (atomicity/nonatomic)

  各参数意义如下:

  readwrite

  产生setter\getter方法

  readonly

  只产生简单的getter,没有setter。

  assign

  默认类型,setter方法直接赋值,而不进行retain操作

  retain

  setter方法对参数进行release旧值,再retain新值。

  copy

  setter方法进行Copy操作,与retain一样


使用assign:对基础数据类型 (NSInteger,CGFloat)和C数据类型(int,float, double, char, 等等)

使用copy: 对NSString

使用retain: 对其他NSObject和其子类



                   参数类型

参数中比较复杂的是retain和copy,具体分析如下:

 

getter 分析


  1、@property(nonatomic,retain)test* thetest;

  @property(nonatomic,copy)test* thetest;

  等效代码:

  -(void)thetest

  {

  returnthetest;

  }

  2、@property(retain)test* thetest;

  @property(copy)test*thetest;

  等效代码:

  -(void)thetest

  {

   [thetestretain];

  return[thetest autorelease];

  }

setter分析

  1、

  @property(nonatomic,retain)test*thetest;

  @property(retain)test* thetest;

  等效于:

  -(void)setThetest:(test*)newThetest {

  if (thetest!= newThetest) {

   [thetestrelease];

  thetest= [newThetest retain];

  }

  }

   2、@property(nonatomic,copy)test*thetest;

  @property(copy)test* thetest;

  等效于:

  -(void)setThetest:(test*)newThetest {

  if (thetest!= newThetest) {

  [thetestrelease];

  thetest= [newThetest copy];

  }

  

nonatomic关键字:

  atomic是Objc使用的一种线程保护技术,基本上来讲,是防止在写未完成的时候被另外一个线程读取,造成数据错误。而这种机制是耗费系统资源的,所以在iPhone这种小型设备上,如果没有使用多线程间的通讯编程,那么nonatomic是一个非常好的选择。



retain
代码说明
如果只是@property NSString*str;
则通过@synthesize自动生成的setter代码为:
-(void)setStr:(NSString*)value{
 str=value;
}
如果是@property(retain)NSString*str;
则自动的setter内容为:
-(void)setStr:(NSString*)v{
 if(v!=str){
   [str release];
   str=[v retain];
 }
}

 

使用assign:对基础数据类型 (NSInteger,CGFloat)和C数据类型(int,float, double, char, 等等)

  使用copy: 对NSString

使用retain:对其他NSObject和其子类


来源:http://blog.csdn.net/daydayupxx/article/details/6635201

posted on 2012-02-20 16:09 淋雨的感觉 阅读(384) 评论(0)  编辑 收藏 引用 所属分类: IOS


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理