OC学习那点事:构造方法和description方法

时间:2021-09-08 14:56:18

1.自定义的构造方法 

Student.m文件: 

@interface Student : NSObject 
{
int _age;
int _no;
}
... …(getter/setter)
//自己写一个构造方法
-(id)initWithAge:(int)age AndNo:(int)no;
@end  

Student.h文件: 

#import "Student.h" 
@implementation Student
... …(getter/setter)
-(id)initWithAge:(int)age AndNo:(int)no
{
//首先调用super的构造方法,然后判断self是否为nil
if (self = [super init])
{
self.age = age;
self.no = no;
}
return self;
}
main.m文件: 

#import <Foundation/Foundation.h> 
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[Student alloc]initWithAge:15 AndNo:2];
NSLog(@"age is %i and no is %i",student.age,student.no);
[student release];
}
return 0;
}

2.重写父类的description方法 

description方法:当使用%@打印一个对象的时候,会调用这个方法 

 在student.m文件中,重写description方法: 

-(NSString *)description 
{
NSString *str = [NSString stringWithFormat:@"age is %i and no %i",_age,_no];
return str;
}

在main.m的main函数中测试: 

Student *student = [[Student alloc]initWithAge:15 AndNo:2]; 
NSLog(@"%@",student);
[student release];
输出: 

2013-07-19 00:02:19.410 构造方法[2446:303] age is 15 and no is 2