@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 方法;

0 1
原创粉丝点击