首页 > 其他 > 详细

objective-C的@property和@synthesize用法

时间:2014-01-28 09:13:13      阅读:370      评论:0      收藏:0      [点我收藏+]

@property相当于声明

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

 

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

bubuko.com,布布扣
#import <Foundation/Foundation.h>

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

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

@end
bubuko.com,布布扣

 

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

 

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

bubuko.com,布布扣
#import <Foundation/Foundation.h>

@interface Student : NSObject

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

@end
bubuko.com,布布扣

 

 

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

bubuko.com,布布扣
#import "Student.h"

@implementation Student

- (int)age {
    return _age;
}

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

@end
bubuko.com,布布扣

 

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

bubuko.com,布布扣
#import "Student.h"

@implementation Student

@synthesize age = _age;

@end
bubuko.com,布布扣

 

不过其实以上的

@synthesize age = _age;

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

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

 

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

比如在setter中添加一句输出(即使getter不变也要写出来):

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

- (int)age {
    return _age;
}
bubuko.com,布布扣

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

bubuko.com,布布扣
@interface Student : NSObject {
    int _age;//添加这行
}

@property int age;

@end
bubuko.com,布布扣

 

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

声明:

bubuko.com,布布扣
@interface Student : NSObject {
    int _age;

    float _height;

}


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

@end
bubuko.com,布布扣

实现:

bubuko.com,布布扣
@implementation Student

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

@end
bubuko.com,布布扣

基本知识,记录一下!

objective-C的@property和@synthesize用法

原文:http://www.cnblogs.com/xiaovid/p/3535332.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!