Objective-C中的@property,@synthesize和点语法
2013-06-10 18:47
288 查看
1.普通的设置器和访问器
Person.h#import <Foundation/Foundation.h> @interface Person : NSObject{ int identify; int age; } - (void)setIdentify:(int) identify; //设置器 - (int)identify; //访问器 - (void)printInfo; @endPerson.m
#import "Person.h" @implementation Person - (void)setIdentify:(int) _identify{ //设置器 identify = _identify; } - (int)identify{ //访问器 return identify; } - (void)printInfo{ //打印identify NSLog(@"Person identify is: %d",identify); } @endMain.m
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); Person *person = [[Person alloc] init]; [person setIdentify:100]; NSLog(@"Person identify: %d",[person identify]); } return 0; }
2. 使用@property和@synthesize来简化设置器和访问器
Person.h#import <Foundation/Foundation.h> @interface Person : NSObject{ int identify; int age; } @property(nonatomic) int identify; @endPerson.m
#import "Person.h" @implementation Person @synthesize identify = _identify; @end
在@property()括号中,可以填写的属性有:
readwrite:默认,便是属性是可读写的,也就是说可以使用getter和setter
readonly: 只读,意味着没有set方法,只能使用getter
assign: 默认,引用计数不增加
retain: 引用计数增加1
原子性: actomic 默认
非原子性:nonatomic,表示不用考虑线程安全问题
assign(缺省),retain,copy是属性如何存储;
atomic是oc中的一种线程保护技术,是防止在未完成的时候,被另外一个线程使用,造成数据错误;
@synthesize是合成的意思,就是编译器自动实现getter和setter函数。
3. 点语法
self.identify = 1; //设置器 相当于[person setIdentify:1]; 调用setIdentify方法self.identify; //访问器 相当于[person identify]; 调用identify方法
点语法是编译器级别
项目中如果想用点语法,必须在项目中的.h文件和.m文件中声明和实现 setIdentify和 identify方法,也就是说要声明和实现getter和setter方法
相关文章推荐
- Objective-C中的@property、@synthesize及点语法
- 黑马程序员——Objective-C学习之@property @synthesize和id及点语法
- 第二章、Objective-C中的@property、@synthesize和dynamic的用法(iOS学习笔记,从零开始)
- Objective-C语言-点语法和变量作用域-@property @synthesize和id
- Objective-c语言_点语法和@property
- objective-c--- 成员变量作用域、@property、@Synthesize、id、重写,自定义构造方法
- Objective-C—self 、super、点语法、成员变量的作用域、@property和@synthesize、id
- objective-c之@synthesize和@property含义
- OC基础语法<1.3> 入门面向对象语法-self、new、 @property和synthesize
- objective-c中的@property,@synthesize等简易用法(八)
- objective-c语法学习:@property属性和点语法
- OC点语法、@property、@synthesize
- 我对Objective-C中的.h、.m、@property、@synthesize的理解
- 【Objective-C学习笔记】核心语法——实例变量作用域、关键字@property和@synthesize
- Objective-C语言_点语法和@property
- 黑马程序员——Objective-C基础——核心语法-@property 和@synthesize
- 黑马程序员--OC自学笔记---05点语法、@property、@synthesize、动态类型、id类型、响应方法、构造方法
- 08-Objective-C特有语法:@property、@synthesize
- objective-c的语法—函数名
- 14、Objective-C语法之KVC使用