PDA

View Full Version : init method question (Hillegass)




GorillaPaws
Mar 19, 2009, 12:52 PM
I'm working through Hillegass and came across this override of the init method in the lottery app.

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

It got me wondering when is it ok to "do work" in the init of a class instead of writing a separate method. My instinct would have been to initialize firstNumber and secondNumber to 0, and to use a separate method call to assign their values to a random number. This would make the code more clear as to when/where the values were being randomized (especially in an app who's primary purpose is generating random numbers).

Thanks in advance for any insight you can share.



lee1210
Mar 19, 2009, 01:00 PM
If any operation on the object depends on those values being set "randomly", then init setting them seems fine to me. Not calling randomize() seems questionable, though.

-Lee