Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Objective-C.Programming.pdf
Скачиваний:
14
Добавлен:
21.02.2016
Размер:
8.64 Mб
Скачать

Deadly init methods

Thus, we arrive at the rules that all stylish Objective-C programmers follow when writing initializers:

If a class has several initializers, only one should do the real work. That method is known as the designated initializer. All other initializers should call, either directly or indirectly, the designated initializer.

The designated initializer will call the superclass’s designated initializer before initializing its instance variables.

If the designated initializer of your class has a different name than the designated initializer of its superclass, you must override the superclass’s designated initializer so that it calls the new designated initializer.

If you have several initializers, clearly document which is the designated initializer in the header.

Deadly init methods

Every once in a while, however, you can’t safely override the superclass’s designated initializer. Let’s say that you are creating a subclass of NSObject called WallSafe, and its designated initializer is initWithSecretCode:. However, having a default value for secretCode is not secure enough for your application. This means that the pattern we have been using – overriding init to call the new class’s designated initializer with default values – is not acceptable.

So what do you do? An instance of WallSafe will still respond to an init message. Someone could easily do this:

WallSafe *ws = [[WallSafe alloc] init];

The best thing to do is to override the superclass’s designated initializer in a way that lets developers know that they have made a mistake and tells them how to fix it:

- (id)init

{

@throw [NSException exceptionWithName:@"WallSafeInitialization" reason:@"Use initWithSecretCode:, not init"

userInfo:nil];

}

215

This page intentionally left blank

30

Properties

In the last chapter, you created a class called Appliance that had two properties: productName and voltage. Let’s review how those properties work.

In Appliance.h, you declared two instance variables to hold the data:

{

NSString *productName; int voltage;

}

You also declared accessor methods for them. You could have declared the accessors like this:

-(void)setProductName:(NSString *)s;

-(NSString *)productName;

-(void)setVoltage:(int)x;

-(int)voltage;

However, you used the @property construct instead:

@property (copy) NSString *productName; @property int voltage;

In Appliance.m, you could have implemented the accessor methods explicitly like this:

-(void)setProductName:(NSString *)s

{

productName = [s copy];

}

-(NSString *)productName

{

return productName;

}

-(void)setVoltage:(int)x

{

voltage = x;

}

-(int)voltage

{

return voltage;

}

217

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]