oc35--自定义构造方法
// // Person.h #import <Foundation/Foundation.h> @interface Person : NSObject @property int age; @property NSString *name; /* 自定义构造方法: 其实就是自定义一个init方法 1.一定是对象方法 2.一定返回id/instancetype 3.方法名称一定以init开头 */ - (instancetype)initHwwAge:(int)age; // 一个类可以有0个或者多个自定义构造方法 - (instancetype)initWithName:(NSString *)name; // 自定义构造方法可以有1个或多个参数 - (instancetype)initWithAge:(int)age andName:(NSString *)name; @end
// // Person.m #import "Person.h" @implementation Person - (instancetype)init { if (self = [super init]) { _age = 10; } return self; } - (NSString *)description { return [NSString stringWithFormat:@"age = %i, name = %@", _age, _name]; } - (instancetype)initHwwAge:(int)age { if (self = [super init]) { _age = age; } return self; } - (instancetype)initWithName:(NSString *)name { if (self =[super init]) { _name = name; } return self; } - (instancetype)initWithAge:(int)age andName:(NSString *)name { if (self = [super init]) { _age = age; _name = name; } return self; } @end
// // main.m // 自定义构造方法 #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { Person *p9 = [Person new];//_age=10,_name=nil Person *p8 = [[Person alloc] init]; p8.age = 20;//_age=10,_name=nil Person *p7 = [[Person alloc] initHwwAge:20];//_age=20,_name=nil Person *p6 = [[Person alloc] initWithName:@"lnj"];//_age=0,_name=@"lnj" Person *p5 = [[Person alloc] initWithAge:20 andName:@"lnj"];//_age=20,_name=@"lnj" NSLog(@"%@", p5); Person *p4 = [[Person alloc] init]; p4.age = 30;//_age=30,_name=nil Person *p3 = [[Person alloc] initHwwAge:30];//_age=30,_name=nil Person *p23 = [[Person alloc] initWithName:@"lmj"];//_age=0,_name=@"lmj" Person *p2 = [[Person alloc] initWithAge:30 andName:@"lmj"];//_age=30,_name=@"lmj" NSLog(@"%@", p2); return 0; }