I am declaring a property in my class in header file;
@property (readonly) NSArray *pages
That’s how I want it to be exposed publicly. Internally though, I am going to allocating it as NSMutableArray so I can add/remove stuff from it. But to do that, I will have to type cast every time. Is there a better way to do this?
Thanks
There isn’t a solution for this. You have to cast every time, or use different properties. Here is a sample for the second approach:
This will be expensive if you access the collection frequently, and may be out of sync with the internal mutable collection (which may be mutated while you iterate on the copy).
Copying can be avoided returning the internal mutable instance (NSMutableArray) disguised as an immutable class (NSArray), but that incurs the following risks:
Note that the following idiom doesn’t solve the problem:
This lets you set the variable, but not use it as a different class than the one declared in the interface. In other words, it forces you to cast on every use: