objective-C的@property和@synthesize用法

@property相当于声明

@synthesize相当于实现set方法和get方法

 

比如有一个Student类,在Student.h文件中,原始的声明方法如下:

#import <Foundation/Foundation.h>

@interface Student : NSObject {
    int _age;//默认为protected
}

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

@end

 

一般成员变量的命名为"_"+名字

 

等效的Student.h文件(使用@property)如下:

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property int age;//注意这里是age不是_age

@end

 

 

相应的原始实现方法的Student.m文件为:

#import "Student.h"

@implementation Student

- (int)age {
    return _age;
}

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

@end

 

等效的Student.m文件(使用@synthesize):

#import "Student.h"

@implementation Student

@synthesize age = _age;

@end

 

不过其实以上的

@synthesize age = _age;

也可以省略,xcode会自动实现。

也就是只需要在Student.h中写好@property的声明,就可以了。xcode会自动设置变量名为:"_"+名字

 

如果要重新实现setter和getter,xcode就不会为你添加@synthesize,那么也就不会自动为你声明变量_age,所以此时就必须在声明文件中添加声明的变量,否则会报错。

比如在setter中添加一句输出:

- (void)setAge:(int)newAge {
    NSLog(@"this is setter.");
    _age = newAge;
}

- (int)age {
    return _age;
}

那么在Student.h中,要添加变量_age的声明:

@interface Student : NSObject {
    int _age;//添加这行
}

@property int age;

@end

 

另外,除了@property和@synthesize实现的基本操作外,还可以添加方法,比如同时设置两个变量的方法:

声明:

@interface Student : NSObject {
    int _age;

    float _height;

}


- (void)setAge:(int)newAge andHeight:(float)newHeight;

@end

实现:

@implementation Student

- (void)setAge:(int)newAge andHeight:(float)newHeight {
    _age = newAge;
    _height = newHeight;
}

@end

基本知识,记录一下!

posted @ 2014-01-28 01:36  xiaovid  阅读(337)  评论(0)    收藏  举报