------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
@synthesize是在m文件中定义set和get方法的实现。
1、@synthesize用法
@synthesize 方法名
1) @synthesize age; 表示生成.h中变量age的get和set方法的实现
注意;
如果是@synthesize的话, 变量名要先在.h文件中声明
<span style="font-size:14px;">@property int age;
@synthesize age;
//展开形式如下:
.h
-(void)setAge:(int)age;
-(int)age;
.m
-(void)setAge:(int)age{
slef->age = age;
}
-(int)age{
return age;
}<span style="font-family: SimSun;"> </span></span><span style="font-size:12px; font-family: SimSun;"> </span>
注意:错误用法,只写了@synthesize,没有写@property ,也没有定义变量 NSString *name;
@property,@synthesize这两个必须是配合使用的
正确用法:
先定义变量int age;
使用@property age;声明方法
使用@synthesize age;实现方法
2、注意事项
1)@property和@synthesize搭配使用,用于简化set和get方法的定义和实现
3、@synthesize指定实例变量赋值
1)@property int a; @synthesize a = _b; 表示用a的get和set方法,修改属性b的值
相当于下面的代码:
- (void)setA:(int)a
{
_b=a;
}
- (int)a
{
return _b;
}
<span style="font-size:14px;">#import <Foundation/Foundation.h>
@interface Person : NSObject
{
//实例变量
NSString *_name;
int _age;
int _weight;
int _b;
int age;
int weight;
NSString *name;
}
//@property 编译器指令,编译器帮我们会进行_age _name get/set方法的声明
@property int age,weight;
@property NSString *name;
//@property int weight;
-(void)test;
@end
@implementation Person
@synthesize age = _b,weight=_weight;
@synthesize name = _name;
-(void)test{
NSLog(@"\n_age = %d,_weight = %d,_name = %@,_b = %d",_age,_weight,_name,_b);
NSLog(@"\nage = %d,name = %@",age,name);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [Person new];
p.age = 18;
p.name = @"xzmly";
p.weight = 180;
NSLog(@"age = %d",p.age);
NSLog(@"name = %@",p.name);
NSLog(@"weight = %d",p.weight);
[p test];
}
return 0;
}</span>