构造方法在创建(实例化)对象的时候,自动调用的方法
带参构造方法
-(instancetype)initWith...
#import <Foundation/Foundation.h>
@interface Person : NSObject{
NSString* _name;
NSInteger _age;
}
//init方法是系统自带的,实现在NSObject类里
//自定义的构造方法需要显示申明
- (instancetype)initWithName:(NSString*)name;
- (instancetype)initWithName:(NSString*)name age:(NSInteger)age;
-(void)showMessage;
@end
@implementation Person
-(instancetype)init{
//self是一个指针 它表示当前调用该方法的对象本身
//super 用来调用父类方法的关键字
self = [super init];
if(self){
NSLog(@"系统自带的构造方法");
_name = @"no name";
_age = 0;
}
return self;
}
//自定义的需要显示申明
- (instancetype)initWithName:(NSString*)name{
self = [super init];
if(self){
NSLog(@"调用自定义的构造函数");
_name = name;
}
return self;
}
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age{
self = [super init];
if(self){
_name = name;
_age = age;
}
return self;
}
- (void)showMessage{
NSLog(@"name:%@ age:%ld",_name,_age);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person* p1 = [Person new];
Person* p2 = [[Person alloc] initWithName:@"dancer"];
Person* p3 = [[Person alloc] initWithName:@"XiaoMing" age:19];
[p1 showMessage];
[p2 showMessage];
[p3 showMessage];
}
return 0;
}
无参构造方法
init->NSObject