12

Can I ask which version I should be using, in my older apps I seem to be using "B" but when I look at a lot of examples online I am seeing a lot of versions that look like "A".

// A
- (id)initWithCoder:(NSCoder *)decoder {
    self=[super initWithCoder:decoder];
    if(self) {
        ...

OR

// B
- (id)initWithCoder:(NSCoder *)decoder {
    self=[super init];
    if(self) {
        ...

2 Answers 2

13

Depends on whether the superclass conforms to the NSCoding protocol or not. If it does, you must call [super initWithCoder:decoder]. If it does not, you must call the superclass' designated initializer.

For example, if your class is a direct subclass of NSObject, you would call [super init], NSObject's designated initializer, since NSObject does not conform to the NSCoding protocol.

Sign up to request clarification or add additional context in comments.

3 Comments

Can I ask, if a class conforms to NSCoding does initWithCoder become its designated initialiser?
No, the designated initializer remains the same.
The Xcode 4 boilerplate for initWithCoder uses [super initWithCoder] regardless of whether the superclass conforms to NSCoding -- took a little while to figure out where it was blowing up.
12

If the superclass adopts NSCoding (which is likely albeit not always the case), always call

[super initWithCoder:decoder]

Otherwise call its designated initializer.

2 Comments

Ah I see, the superclass is NSObject (which from what I can tell does not conform to NSCoding) so in this case I should use "B". Much appreciated, a very clear / concise answer.
NSObject is don't like init withCoder,aha:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.