Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a default init function in iOS

Tags:

ios

originally, I have a default init function

 -(id) init
   {
    if (self=[super init])
    {
      ......
     }
    return self;
   }

However, I like to override the init function to pass in custom objects or other objects like

 -(id) initWithScore:(NSString*) score
    {
    if (self=[super init])

Now there is an error saying [super init] function can only be called with -(id) init function.

So what do I do to fix it so I can pass in objects and also use self=[super init]?

Error:Cannot assign to self outside of a method in the init family.

like image 721
jason white Avatar asked Nov 28 '22 09:11

jason white


2 Answers

I was trying to convert a projet to ARC and after creating a new one and including the files from the old one - one of the issues i got was

Cannot assign to 'self' outside of a method in the init family

The selector name MUST begin with init - not only that in my case the init selector was:

-(id)initwithPage:(unsigned)pageNum {...}

Notice the small 'w'.

I have changed it to:

-(id)initWithPage:(unsigned)pageNum {...}

Notice the capital 'W'!

My problem was solved.

I hope this helps someone.

like image 182
Sasho Avatar answered Dec 09 '22 09:12

Sasho


You need to return an object of type id in your new method.

Suppose you have declare an NSString *myscore property, you will write something like this:

-(id) initWithScore:(NSString*) score
 {
    self=[super init];
    if (self)
    {
       self.myscore = score;
    }
    return self;
}
like image 31
tiguero Avatar answered Dec 09 '22 10:12

tiguero