Property initializing in some function

Discussion in 'Mac Programming' started by sam256, Oct 4, 2011.

  1. sam256 macrumors newbie

    Joined:
    Oct 4, 2011
    #1
    If we initialize class property, created using
    Code:
    @property (nonatomic, retain) NSArray *prop
    in the body of function
    Code:
    (void)init
    in this way
    Code:
    prop = [NSArray arrayWithObjects:@"1", @"2", nil]
    where will be a mistake in this code. What consequences in working program it will have and in what time moment, in what function will it happen?
     
  2. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    It seems really clever to just write "prop", but after a few years of programming you will find it much better if a line of code clearly states what it does, like "self.prop" does. What's the variable behind that property called? It's not called "prop" as well, is it? In that case you are setting yourself up for trouble.
     
  3. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #3
    There's a couple of problems with code.

    Firstly you're assigned an autoreleased object to an instance variable without retaining it. At some point the object whose address in prop will be released and then prop will point to a zombie. If you try to send a message to this object after it's begin released, your program is likely to crash. When? How knows. It might seems like your program is crashing randomly.

    "But the property is retain!" I hear you say. Yes, but you're bypassing the property and assessing the instance variable directly.

    You need to do one of the following (in ascending order of my preference).

    Either:
    Code:
    prop = [[NSArray arrayWithObjects:@"1", @"2", nil] retain];
    or:
    Code:
    prop = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
    or
    Code:
    self.prop = [NSArray arrayWithObjects:@"1", @"2", nil];
     
  4. sam256 thread starter macrumors newbie

    Joined:
    Oct 4, 2011
    #4
    Dear gnasher729, jiminaus, thank you so much for your answers, they were very helpful!!!))
     

Share This Page