2015-02-26 2 views
0

Я унаследовал этот код:Objective-C: Почему бы не назвать назначенный инициализатор?

- (id)initWithLocation:(CLLocation *)inLocation { 
    if (self = [super init]) 
    { 
     _location = [inLocation copy]; 
    } 
    return self; 
} 

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset { 
    if (self = [super init]) 
    { 
     _location = [inLocation copy]; 
     _offset = [offset copy]; 
    } 
    return self; 
} 

и мне интересно, если есть хорошая причина, почему первый метод не вызывает обозначенный инициализатору (например, как этот Is it okay to call an init method in self, in an init method?)?

то почему бы не сделать это:

- (id)initWithLocation:(CLLocation *)inLocation { 
    if (self = [super init]) 
    { 
     [self initWithLocation:inLocation offsetValue:nil]; 
    } 
    return self; 
} 

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset { 
    if (self = [super init]) 
    { 
     _location = [inLocation copy]; 
     _offset = [offset copy]; 
    } 
    return self; 
} 

ответ

2

Метод - (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset должен быть назначен инициализатором и - (id)initWithLocation:(CLLocation *)inLocation должны назвать это так:

- (id)initWithLocation:(CLLocation *)inLocation { 
    return [self initWithLocation:inLocation offsetValue:nil]; 
} 

Он также считается хорошей практикой, чтобы отметить назначенный инициализатору в интерфейсе класса с использованием NS_DESIGNATED_INITIALIZER:

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset NS_DESIGNATED_INITIALIZER; 
+1

Учитывая, что ответы все одинаковы, я выбираю этот, так как он упоминает NS_DESIGNATED_INITIALIZER. – Snowcrash

0

гораздо более подходящим способом было бы так:

- (id)initWithLocation:(CLLocation *)inLocation { 
    return [self initWithLocation:inLocation offsetValue:nil]; 
} 

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset { 
    if (self = [super init]) { 
     _location = [inLocation copy]; 
     _offset = [offset copy]; 
    } 
    return self; 
} 
0

Все, что вам на самом деле нужно сделать, это ...

- (id)initWithLocation:(CLLocation *)inLocation { 
    return [self initWithLocation:inLocation offsetValue:nil]; 
} 

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset { 
    if (self = [super init]) 
    { 
     _location = [inLocation copy]; 
     _offset = [offset copy]; 
    } 
    return self; 
} 

И ты прав. В этом случае нет причин.