이것은 init 메소드에 init…
의 super
의 구현을 호출하여 수행됩니다
//Car.m:
- (id)initWithData:(NSDictionary *)carData {
self = [super init];
if (self) {
//setup generic car properties:
self.wheels = [carData objectForKey:@"wheels"]; //example
self.bumpers = [carData objectForKey:@"bumpers"]; //example
}
return self;
}
+ (id)carWithData:(NSDictionary *)carData {
return [[[self alloc] initWithData:carData] autorelease];
}
//Lexus.m:
- (id)initWithData:(NSDictionary *)carData {
//this call to super is where the car's generic properties get initialized:
self = [super initWithWithData:carData];
if (self) {
//setup lexus car properties:
self.navigation = [carData objectForKey:@"navigation"]; //example
}
return self;
}
//there is no need to override super's [carWithData:] method as it's only a wrapper anyway.
또한 모두 initWith…
및 carWith…
방법 id
하지 Car
또는 Lexus
를 반환 있습니다. 코드가 설정되는 방식으로 캐스팅 문제가 발생합니다. [Lexus carWithData:dataDict]
은 Lexus
클래스의 개체를 반환하지만 컴파일러는 Car
을 예상하므로 컴파일러는 알지 못합니다. 서브 클래스의 구현은 여기에
- (id)initWithData:(NSDictionary *)carData;
{
self = [super initWithData:carData];
if (self) {
_navigation = [carData valueForKey:@"navigation"];
}
return self;
}
+ (id)carWithData:(NSDictionary *)carData;
{
return [[[self alloc] initWithCarData:carData] autorelease];
}
아, 나는 당신이 실제로 클래스 메소드 내에서'[self alloc]'을 할 수 있는지 모른다. 나는이 대답이 가장 깨끗하다고 생각한다. – pixelfreak
@pixelfreak : 물론 가능합니다. C++과는 달리 Objective-C에는 클래스 메소드 호출에 대한 제한이 없습니다. – Regexident
@pixelfreak : Objective-C에서'self'는 ** 인스턴스 메소드 **에있을 때의 ** 인스턴스 객체 **와 ** 클래스 메소드 **에있을 때 ** 클래스 객체 **를 참조합니다. Objective-C 클래스는 실제로 객체 자체임을 기억하십시오. – Regexident