init method question (Hillegass)

Discussion in 'Mac Programming' started by GorillaPaws, Mar 19, 2009.

  1. GorillaPaws macrumors 6502a


    Oct 26, 2003
    Richmond, VA
    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.
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.


Share This Page