Objective-C : Convenience init

준우·2024년 5월 16일

Objective-C 이야기

목록 보기
9/19
post-thumbnail

Convenience init

Objc-C에서는 프로퍼티 및 클래스 초기화를 간소화하고 다양한 초기화 방법을 제공함.

Objc-C 초기화를 하는 방법은 두 가지가 있음.

지정(Initializer) 메서드와 편의(Convenience) 생성자임.

지정(initializer) 메서드

  • 클래스의 주요 초기화 메서드임.
  • 모든 필수 프로퍼티를 초기화하고 상위 클래스의 초기화 메서드를 호출함.
// 전체 초기화
- (id)init
{
    self = [super init];
    if (self) {
        age = 0;
        name = @"이름없음";
    }
    return self;
}

편의(convenience) 생성자

  • 지정 초기화 메서드를 호출하여 객체를 초기화함.
  • 주로 클래스 내에서 간편한 초기화를 제공하기 위해 사용됨.
// Age 만 초기화
- (id)initWithAge:(int)ageValue{
    self = [super init];
    if (self) {
        age = ageValue;
        name = @"이름없음";
    }
    return self;
}

// Name 초기화
- (id)initWithName:(NSString *)nameValue{
    self = [super init];
    if (self) {
        age = 0;
        name = nameValue;
    }
    return self;
}

// Age, Name 초기화
- (id)initWithNameAndAge:(NSString *)nameValue age:(int)ageValue{
    self = [super init];
    if (self) {
        age = ageValue;
        name = nameValue;
    }
    return self;
}

생성자 사용은 어떻게 할까??

Cat * myCat1 = [[Cat alloc] init];
Cat * myCat2 = [[Cat alloc] initWithAge:2];
Cat * myCat3 = [[Cat alloc] initWithName:@"개냥이"];
Cat * myCat4 = [[Cat alloc] initWithNameAndAge:@"야옹이" age:3];

0개의 댓글