【Lession 09 OC语言】@property与@synthesize

本节目录


@property

前面写一个age属性,又要写set/get方法,比较麻烦,@property就是简化操作的

Staff.h

#import <Foundation/Foundation.h>

@interface Staff : NSObject

@property int age;

@end

上面的代码等效于在头文件声明了age的set/和get方法

-(void)setAge:(int)newAge;
-(int)age;

 

@synthesize

在头文件声明了age的set/get方法后,在点.m文件中要实现get/set方法,@synthesize就是自动来为你做这事的。

Staff.m

#import "Staff.h"

@implementation Staff
@synthesize age = _age;

@end

@synthesize age相当于

-(void)setAge:(int)newAge{
    age = newAge;
}
//-(void)setAge:(int)age{_age = age;}
-(int)age{
    return age;
}

 

main函数运行

#import <Foundation/Foundation.h>
#import "Staff.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Staff *staff = [[Staff alloc] init];
        [staff setAge:132];
        NSLog(@"age: %i",staff.age);
        [staff release];
        
    }
    
    return 0;
}

 

注:-(void)setAge:(int)newAge方法中的newAge可以随便写,只要方法名正确就可以

 

但在xcode4.5以后 @synthesize已经很少用了,xcode4.5后,在.m文件中会自动实现set/get方法,并且会生成一个带下划线的age成员变量(_age)

1 #import "Staff.h"
2 
3 @implementation Staff
4 
5 -(void)setAge:(int)age{
6     _age = age;
7 }
8 @end

 

第6行的下划线是xcode自动生成的

posted @ 2014-03-17 16:11  Vincent_Guo  阅读(189)  评论(0编辑  收藏  举报