Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ramy1989

macrumors newbie
Original poster
Nov 7, 2012
21
0
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?
 

gnasher729

Suspended
Nov 25, 2005
17,980
5,565
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?

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].
 

xStep

macrumors 68020
Jan 28, 2003
2,031
143
Less lost in L.A.
And please don't use "new". Use one of the convenience methods, like [NSMutableArray array].

There is nothing wrong with using "new".

----------

What's the difference?

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.
 
Last edited:

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
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.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.