1.重写构造方法
init开头
动态方法:对象调用
静态方法:类名调用 分配内存
- (动态方法)
+ (静态方法)
id表示任何对象
-(id)initWithAge:(int)age andNo:(int) no;
- (id) initWithAge:(int)age andNo:(int) no{
//首先要调用super的构造方法
//self指向当前对象
self=[super init]; //内存出问题,可能self为空,所以要先判断是否成功分配内存
_age=age;
_no=no;
return self;
}
-(id) initWithAge:(int)age andNo:(int)no{
self = [super init]; //super的构造方法
if(self){ //判断对象是否为空
// if(self=[super init])
_age=age;
_no=no;
}
return self;
}
@autoreleasepool{
Student *stu=[[Student alloc] initWithAge:15 andNo:2];
}
2.直接将对象的所有值打印出来
//%@表示打印一个OC对象
NSLog(@"%@",stu); //打印出对象的地址
重写父类的description方法
当使用%@带打印一个对象的时候嗲用description方法;
NSString 相当与string char *s="wxd";
NSString *str=@"wxd";
-(NSString *)description{
//return @"wxd";验证是否调用这个方法;
NSString * str = [NSString stringWithFormat:@"age is %i and no is %i",_age,_no];
return str;
}