Question

I use the following to expose languages array.

@property(nonatomic,readonly)NSArray *languages;

Assigning languages before ARC was like this:

languages=[[NSArray arrayWithObjects:
               [[Language alloc]initWithCode:@"es"],
               [[Language alloc]initWithCode:@"en"],
               nil] retain];

So, I was both able to retain the object and also mark it as readonly to outside.

With ARC, As I cannot type "retain" manually. How can I do this without overriding setters and getters? Is there a way to mark a property both readonly (to outside) and retain (to inside) for ARC?

Was it helpful?

Solution

retain* and readonly really have nothing to do with each other. readonly indicates that the property only has a getter, not a setter. retain means that the class maintains a retaining (strong) reference to the object referenced by the property, and under ARC, assuming the property is backed by an underlying, synthesized instance variable, means that the instance variable is a __strong variable.

If you want a property that is read-only to the outside world, but can be read and written inside the class, you can redeclare the property as readwrite in a class extension in your implementation (.m) file. In the header:

@property (nonatomic, strong, readonly) NSArray *languages;

Then, at the top of your .m:

@interface YourClass ()
    @property (nonatomic, strong, readwrite) NSArray *languages;
@end

Inside the class's implementation, you can now use self.languages = ...;, (or _languages = ...; in the initializer) to set the languages property. This is not actually different under ARC vs. non-ARC...

*Under ARC, it's more customary to use strong instead of retain, but the compiler treats them the same way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top