自定义构造方法
当想让对象一创建就拥有一些值的时候,为们可以自定义构造方法
例如:人物一创建就拥有年龄和姓名
在.h中
@interface Person : NSObject
@property(nonatomic,copy)NSString * name
@property(nonatomic,assign)int age;
-(id)initWithAge: (int)age andName : (NSString *)name
@end
在.m中
@implementation Person
-(id)initWithAge : (int)age andName : (NSString *)name
{
if(self = [super init])
{
_age = age;
_name = name;
}
return self;
}
//重写description方法是为了方便打印对象信息
-(NSString *)description
{
return [NSString stringWithFormat:@“age = %d,name = %@“,_age,_name];
}
@end
在main中
Person * p = [[Person alloc] initWithAge:30 andName:@“小明”];
NSLog(@“%@“,p);//打印对象的话要在.m中重写description方法
>继承关系中的自定义构造方法
例如
A类
@interface A : B
//A还有个姓名
@property(nonatomic,copy)NSString * name;
-(id)initWithAge:(int)age andName:(NSString *)name;
@end
@implementation A
-(id)initWithAge:(int)age andName(NSString *)name
{
if(self = [super init])
{
//这个时候_age是父类中通过property自动生成的,并且存在.m中,是私有的无法继承,所以不能直接访问,会报错.
//_age = age;
//可以这么写
[self setAge:age];
_name = name;
}
return self;
}
@end
B类
@@interface B : NSObject
@property(nonatomic,assign)int age;
@end
如果在B中,有过重写init方法,还可以有优化为
例如
B中
@interface B : NSObject
@property int age;
-(id)initWithAge;
@end
@implementation B
-(id)initWithAge
{
if(self = [super init])
{
_age = age;
}
return self;
}
@end
则在A中可以这么写
@interface A : B
@property(nonatomic,copy)NSString * name;
-(id)initWithAge:(int)age andName : (NSString * )name;
@end
在.m中
@implementation A
-(id)initWithAge:(int)age andName:(NSString *)name
{
//直接调用父类的initWithAge方法
if(self = [super initWithAge:age])
{
_name = name;
}
return self;
}
@end |
|