How do I retain a readonly property?

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

  1. ramy1989 macrumors newbie

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

    @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:

    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. gnasher729 macrumors P6


    Nov 25, 2005
    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. ramy1989 thread starter macrumors newbie

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

    xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    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. lee1210 macrumors 68040


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


Share This Page