黑马程序员技术交流社区
标题:
@property关键字介绍及使用
[打印本页]
作者:
花——九
时间:
2015-10-19 23:17
标题:
@property关键字介绍及使用
@property关键字介绍及使用
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [Person new];
p.name = @"凤姐"; //[p setName:@"凤姐"];
p.age = 18;
p.weight = 80.3f;
p.height = 2.5f;
p.sex = 1;
NSLog(@"name = %@,%d,%.2f,%.2f,%d",p.name,p.age,p.weight,p.height,p.sex); // [p name];
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
//实例变量
NSString *_name;
int _age;
float _height;
float _weight;
int _sex;
}
//提供对实例变量操作的对外的接口
//-(void)setAge:(int)age;
//-(void)setHeight:(float)height;
//-(void)setWeight:(float)weight;
//-(void)setSex:(int)sex;
//
//-(int)age;
//-(float)height;
//-(float)weight;
//-(int)sex;
//生成_name的get和set方法的声明
@property NSString* name;
//-(void)setName:(NSString *)name;
//-(NSString *)name;
@property int age,sex;
@property float height,weight;
//@property float weight;
//@property int sex;
//注意:如果 @property 都是同一个类型的,可以放到一行上,用逗号分隔,而不需要写多行的@property
+(void)run;
@end
#import "Person.h"
@implementation Person
//提供对实例变量操作的对外的接口
-(void)setName:(NSString *)name{
_name = name;
}
-(void)setAge:(int)age{
_age = age;
}
-(void)setHeight:(float)height{
_height = height;
}
-(void)setWeight:(float)weight{
_weight = weight;
}
-(void)setSex:(int)sex{
_sex = sex;
}
-(NSString *)name{
return _name;
}
-(int)age{
return _age;
}
-(float)height{
return _height;
}
-(float)weight{
return _weight;
}
-(int)sex{
return _sex;
}
@end
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2