@synthesize & @dynamic 使用对比
来源:互联网 发布:sqlserver存储过程作用 编辑:程序博客网 时间:2024/06/13 06:14
@synthesize 在使用上 @dynamic 有一定的差别,其实也就是@synthesize默认做了一些@dynamic的一些工作。 具体默认做了什么工作,对比之后就会发现:
先看一段@synthesize的实现:
ViewController.h 代码:
#import <UIKit/UIKit.h>#import "EMPlane.h"@interface ViewController : UIViewController@property(nonatomic, retain) EMPlane* plane;@end
ViewController.m 代码:
@implementation ViewController@synthesize plane = plane;- (void)viewDidLoad{ [super viewDidLoad]; self.plane = [[EMPlane alloc]init]; NSLog(@"viewDidLoad plane address=%p, plane count=%d", self.plane, [self.plane retainCount]); [self.plane release]; NSLog(@"viewDidLoad plane count=%d after", [plane retainCount]);}
再看一段使用 @dynamic 实现与其等同的代码
ViewController.h 代码:
#import <UIKit/UIKit.h>#import "EMPlane.h"@interface ViewController : UIViewController{ EMPlane* plane;}@property(nonatomic, retain) EMPlane* plane;@end
ViewController.m 代码:
@implementation ViewController@dynamic plane;-(void)setPlane:(EMPlane *)newPlane{ if(plane!=newPlane) { [plane release]; plane = [newPlane retain]; NSLog(@"setPlane plane address=%p, plane count=%d", plane, [plane retainCount]); }}-(EMPlane*)plane{ return plane;}- (void)viewDidLoad{ [super viewDidLoad]; self.plane = [[EMPlane alloc]init]; NSLog(@"viewDidLoad plane address=%p, plane count=%d", self.plane, [self.plane retainCount]); [self.plane release]; NSLog(@"viewDidLoad plane count=%d after", [plane retainCount]);}
上述代码需要小结:
1:程序中定义 "变量类型*变量名;" , 使用@synthesize 变量名;然后他会默认生成的代码名称符合如下格式:
//get方法:
-(变量类型*) 变量名()
{
return 变量名;
}
//set方法:
-(void) set变量名(变量类型*newValue) //注意这里的变量名首字母是大写的
{
//具体的实现方式根据@property的属性不同而不同, copy, retain, strong, assign,nonatomic, atomic等。
}
2:当程序中使用 self.变量名与直接 变量名 是不一样的。
self.变量名: 访问的是属性方法,具体是get还是set就需要看是写在左边还是右边了。
变量名:访问的就是属性本身。
3:具体 set的方法实现与@property 具体声明有关。具体请参见:
ios 5.1 Libray-> Languages&Utilities -> Objective-C -> The Objective-C Programming Language-> Declared Properties
4:@synthesize 相对于@dynamic 而前,自动添加申明属性变量,同时还为其添加了get 与 set 方法;
- @synthesize & @dynamic 使用对比
- @dynamic、@synthesize
- Objective-C使用@dynamic和@synthesize
- objective-c 使用@dynamic和@synthesize
- objective-c 使用@dynamic和@synthesize
- Objective-C使用@dynamic和@synthesize
- 浅析 @synthesize 与 @dynamic
- @dynamic与@synthesize
- @synthesize和@dynamic区别
- @dynamic与@synthesize
- @synthesize和@dynamic区别
- @synthesize和@dynamic区别
- @synthesize和@dynamic区别
- @synthesize和@dynamic区别
- @synthesize和@dynamic区别
- @synthesize、 @dynamic 的使用方法
- @property @synthesize @dynamic
- @synthesize和@dynamic区别
- eclipse 背景颜色配置
- 6 cocos2dx 菜单项
- @PathVariable和@RequestParam的区别
- Node JS 入门——window下环境搭建
- WM_PAINT介绍及OnPaint()函数的作用原理
- @synthesize & @dynamic 使用对比
- javax.el.ELException: Cannot convert 4028b8813d13fb64013d154023c50035 of typ
- C#委托调用实例
- iOS 图像处理
- 狗爹这名字取得好难听
- 在Spring中结合Dbunit对Dao进行集成单元测试
- java利用飞信接口发送短信
- 揭秘:4家企业新项目获得阿里云创投资金
- 深入理解JVM学习笔记——第十三章 线程安全与锁优化