2015-01-05 4 views
0

Objective C 기술을 연습하면서 작은 문제가 생겼습니다. 어디서나이 문제에 대한 정답을 찾을 수는 없습니다. 내가 읽은 Apple 개발자 가이드에는 여러 매개 변수 (예 : 3 개의 매개 변수)가있는 클래스 팩터 리 메서드를 사용하고 재정의 된 init 메서드를 통해 초기화 된 개체를 반환하는 방법이 나와 있습니다.여러 매개 변수가있는 클래스 팩터 리 메서드

여기에는 XYZPerson이라는 간단한 클래스가 있습니다.

@implementation XYZPerson 

// Class Factory Method 
+ (id)person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth { 
    // need to return [ [self alloc] init with the 3 paramaters]; here 
    // Or some other way to do so.. 
} 

// Overridden init method 
- (id)init:(NSString *)firstName with:(NSString *)lastName andWIth:(NSDate *)dateOfBirth { 
    self = [super init]; 

    if (self) { 
     _firstName = firstName; 
     _lastName = lastName; 
     _dateOfBirth = dateOfBirth; 
    } 

    return self; 
} 

// Use the initialized instance variables in a greeting 
- (void)sayHello { 
    NSLog(@"Hello %@ %@", self.firstName, self.lastName); 
} 

그리고 내 주요 내가

XYZPerson *person = [XYZPerson person:@"John" with:@"Doe" andWith:[NSDate date]]; 
[person sayHello]; 

아무도 나에게 올바르게이 작업을 수행하는 방법에 작은 포인터를 제공 할 수있는 XYZPerson 객체를 인스턴스화하고있는?

+ (id)person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth { 
    XYZPerson *result = [[self alloc] init:firstName with:lastName andWith:dateOfBirth]; 

    return result; 
} 

는 ARC를 사용하지 않는 경우에서, returnautorelease를 추가 : 나는 당신의 질문을 이해하면

답변

1

, 다음과 같은합니다.

BTW - init 메서드의 반환 형식을 id 대신 instancetype으로 변경하십시오.

+1

위 메소드의 반환 유형을'instancetype'으로 변경할 수도 있습니다. – Fabian

+0

감사합니다. –

+0

기꺼이 도와 드리겠습니다. 대답을 수락하는 것을 잊지 마십시오. – rmaddy

0
@implementation XYZPerson 

// Class Factory Method 
+ (instanceType) person:(NSString *)firstName with:(NSString *)lastName andWith:(NSDate *)dateOfBirth { 

return [[[self class] alloc]init: firstName with: lastName andWith:dateOfBirth]; 

} 

- (instanceType) init:(NSString *)firstName with:(NSString *)lastName andWIth:(NSDate *)dateOfBirth { 
    self = [super init]; 

    if (self) { 
     _firstName = [firstName copy]; 
     _lastName = [lastName copy]; 
     _dateOfBirth = [dateOfBirth copy]; 
//nb added copy to each of these, we do not own these objects, they could be lost to us.. 

/// or you could do this instead.. 
//assuming you synthesised getters/setters for (strong) properties.. 

[self setFirstName:firstName]; 
[self setLastName:lastName]; 
[self setDateOfBirth: dateOfBirth]; 

    } 

    return self; 
} 
+0

나는 [자기 계급]이 여기에 적절하다고 생각하지 않는다. self는 클래스 (+) 메소드에서 XYZperson의 인스턴스가 아닙니다. –

관련 문제