构造方法:用来初始化对象的方法,是个对象方法,-开头 重写构造方法的目的:为了让对象创建出来,成员变量就会有一些固定的值 重写构造方法的注意点: 1.先调用父类的构造方法([super init]) 2.再进行子类内部成员变量的初始化 自定义构造方法 命名规范: 1.一定是对象方法,一定以“-”开头 2.返回值一般是id开头 3.方法名一般以initwith开头 #import <Foundation/Foundation.h> #import “Person.h” @interface Person : NSObject @property NSString *name; @property int age; - (id)init; - initWithName:(NSString *)name; - initWithAge:(int)age; - initWithName:(NSString*)name andAge:(int)age; @end @implementation Person - initWithName:(NSString*)name andAge:(int)age { if( self = [super init] ) { _name = name; _age = age; } return self; } - initWithAge:(int)age { if( self = [super init] ) { _age = age; } return self; } - initWithName:(NSString *)name { if( self = [super init] ) { _name = name; } return self; } - (id)init { if ( self = [super init] ) { _name = @“Jack”; } return self; } @end int main() { @autoreleasepool { Person *p = [[Person alloc] initWithName:@“Rose”]; Person *p1 = [[Person alloc] initWithAge:18]; Person *p2 = [[Person alloc] initWithName:@“Rain” andAge:20]; NSLog(@“00000”); } return 0; }
|