error: the result of a delegate init call must be immediately returned or assigned to 'self'
Asked Answered
D

1

6

What does this mean? How do I fix it?

Code:

- (id)init
{
    [super init];
    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    return self;
}

Error:

/Users/user/Dropbox/dev/bignerdranch_cocoa/lottery/LotteryEntry.m:15:5:{15:5-15:17}: error: the result of a delegate init call must be immediately returned or assigned to 'self' [4]
Disappointment answered 8/11, 2011 at 22:9 Comment(2)
Is the book 'Cocoa Programming for Mac OS X, Third Edition'? I'm doing the exact same tutorial and got the same error which led me here. Thanks for your help Steve. I'm finding objective-c a bit more different than I expected coming from java and C#.Observe
@wy125 I am not sure what edition this was from but a 6th edition? came out recently for xcode 4 that has been making things a bit easier for me.Disappointment
C
24

Your self was not created ...

-(id) init {
  self = [super init];
  if(self != nil) {
    // do init stuff
  }
  return self;
}
Colman answered 8/11, 2011 at 22:15 Comment(5)
Thanks. I'm doing a tutorial out of a book... is this problem because the book is out of date with the latest xcode or just written wrong?Disappointment
Sounds like the book has a typoRileyrilievo
@ian: There used to be a disagreement on whether you should assign self to a value in your init method. Some say you should never assign self, others say you should. In most cases, it doesn't matter whether you do or not (i.e., both code samples are fine). However, Apple recommends that you do, and thus that warning exists in its compiler.Olivia
@ian: To wit, there's a big (and classic) discussion about this issue here: wilshipley.com/blog/2005/07/self-stupid-init.htmlOlivia
@mipadi: It's not just some "recommendation". You definitely need to assign the result of init to self, because an init method is allowed to release the object it is called on and return a different object.Goldshell

© 2022 - 2024 — McMap. All rights reserved.