在XCode4.5以上,写了@property之后,系统会自动生成私有_字段和实现@synthesize方法
但如果自己写了set或者get方法之后,就不会帮你产生默认的下划线字段
Student.h:
#import <Foundation/Foundation.h> @interface Student : NSObject{ @public //以下就是共有类型 还有@private和@protected int _age; int _no; } @property int age;//自动申明getter和setter方法 @property int no; //-(int)age; //-(int)no; ////OC里面没有构造方法 //-(void)setAge:(int)newAge; //setAge:是它的方法名(注意要带上冒号) //-(void)setNo:(int)newNo; // //-(void)setAge:(int)newAge AndNo:(int)newNo; //setAge: AdnNo:是它方法名 -(id)initWithAge:(int)newAge andWithNo:(int)newNo; //-(NSString *)description; @end
Student.m:
#import "Student.h" @implementation Student @synthesize age=_age,no=_no;//自动实现setter和getter方法 //#pragma mark - setter //#pragma mark 设置年龄 //-(void)setAge:(int)newAge{ // age=newAge; //} //#pragma mark 设置学号 //-(void)setNo:(int)newNo{ // no=newNo; //} //#pragma mark 设置年龄跟学号 //-(void)setAge:(int)newAge AndNo:(int)newNo{ // age=newAge; // no=newNo; //} //#pragma mark - getter //#pragma mark 获得学号 //-(int)no{ // return no; //} //#pragma mark 获得年龄 //-(int)age{ // return age; //} #pragma mark - 构造方法 #pragma mark 通过传入年龄和学号初始化一个构造方法 -(id)initWithAge:(int)newAge andWithNo:(int)newNo{ if(self=[super init]) //首先要初始化父类方法 { _age=newAge; _no=newNo; return self; } return nil; } //重写父类的description方法 //-(NSString *)description{ // NSString * str =[NSString stringWithFormat:@"age is %i and no is ",self.age,self.no]; // return str; //} @end
main:
#import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student * student=[[[Student alloc] initWithAge:20 andWithNo:1] autorelease]; //自动释放 NSLog(@"this student age=%i,and no=%i",[student age],[student no]); NSLog(@"age=%i,no=%i",student.age,student.no); NSLog(@"%@",student);//打印内存地址 //[student release];//防止内存泄漏,要释放该对象内存 } return 0; }
结果:
2013-08-02 15:55:34.918 @property[1396:303] this student age=20,and no=1
2013-08-02 15:55:34.919 @property[1396:303] age=20,no=1
2013-08-02 15:55:34.920 @property[1396:303] <Student: 0x100109970>
时间: 2024-12-10 00:13:24