How do I retain a readonly property?

Discussion in 'Mac Programming' started by ramy1989, Dec 23, 2012.

  1. macrumors newbie

    Joined:
    Nov 7, 2012
    #1
    Let's say that I jave this property:

    Code:
    @property(nonatomic,strong,readonly) NSMutableArray* tags;
    
    I need to retain it only in the init method, because it's the only place where I assign it.How do I retain it then? I should write:

    Code:
    self.tags=[NSMutableArray new];
    
    But this is a syntax error because there isn't any setter.How to allow the setter to operate only in the init method?
     
  2. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    In the public header file, you make it readonly. In the implementation file, you make it read/write.

    And please don't use "new". Use one of the convenience methods, like [NSMutableArray array].
     
  3. thread starter macrumors newbie

    Joined:
    Nov 7, 2012
    #3
    What's the difference?
     
  4. xStep, Dec 23, 2012
    Last edited: Dec 23, 2012

    macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #4
    There is nothing wrong with using "new".

    ----------

    new will alloc, init, and retain the object. array should not retain the object beyond the method. This is important when using manual memory management.
     
  5. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #5
    I don't know that anyone answered the question. Using the . notation to access a property this is converted to [self propertyName] on an access or [self setPropertyName] on assignment. Normally using self.propertyName in methods of the class is fine, but obviously when there's no setter you can't use this syntax. When you are in methods in the object itself, propertyName = someValue should be fine. The readonly really means "other people". If you weren't using properties, and you had an instance variable, and wrote an accessor, but no mutator, you wouldn't have any problem. You'd just assign to the variable in your instance methods. The properties are just syntactic sugar for the same thing. All the modifiers just describe what getter/setter methods are generated, whether they make copies, how they manage memory, etc. You could do all of this yourself, the properties are just a shortcut.

    TL;DR: Remove self. and proceed.

    -Lee
     

Share This Page