@synthesize & @dynamic 使用对比

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值