1. 程式人生 > >OC學習筆記,建構函式

OC學習筆記,建構函式

建構函式用與在宣告一個物件時候,為這個物件進行初始化。

預設建構函式是init。

也可以自定義建構函式,通常規定已init開頭。

@interface Person : NSObject {
@private
    // 把_age _name包裝起來,外部不能使用
    // 確保了安全性
    // 欄位field 成員變數
    int _age;
    NSString *_name;
}
// 向外面暴露的成員方法
// setAge:和setAge這2個方法是我們對_age欄位提供的2個函式。

// 建構函式
- (id) init;
- (id) initWithName:(NSString *)newName;
- (id) initWithName:(NSString *)newName withAge:(int)newAge;

- (void) setAge:(int)newAge;
- (int) getAge;
- (void) setName:(NSString *)newName;
- (NSString *) getName;

- (void) setName:(NSString *)newName withAge:(int)newAge;
@end
上面.h檔案中 init 和 initWithName: 以及 initWithName:withAge:都是建構函式。

分別是無參,一個引數,兩個引數。

在.m檔案中對這些函式進行實現。

@implementation Person

- (id) init {
    return [self initWithName:@"無名氏"];
}

- (id) initWithName:(NSString *)newName {
    return [self initWithName:newName withAge:-1];
}

// 建構函式實現部分只寫一次,其他方法相互呼叫
- (id) initWithName:(NSString *)newName withAge:(int)newAge {
    self = [super init];
    if (self) {
        [self setName:newName withAge:newAge];
        NSLog(@"在建構函式中 name %@ age %d %s", _name, _age, __FUNCTION__);
    }
    return self;
}

- (void) setAge:(int)newAge{
    _age = newAge;
}
- (int) getAge{
    return _age;
}
- (void) setName:(NSString *)newName {
    _name = newName;
}

- (NSString *) getName {
    return _name;
}
- (void) setName:(NSString *)newName withAge:(int)newAge {
    [self setName:newName];
    [self setAge:newAge];
}

@end

在main函式中宣告建立物件即可。
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *xiaoming = [[Person alloc] init];
        [xiaoming setAge:20];
        [xiaoming setName:@"小明"];
        
        Person *xiaoli = [[Person alloc] init];
        [xiaoli setName:@"小李" withAge:30];
        
        Person *xiaozhang = [[Person alloc] initWithName:@"小張" withAge:50];
        
    }
    return 0;
}