Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C @property for to-many relationships

I've had various cases where an Objective-C class has a property that needs to be a collection class (NSArray usually). Is there a standard way to implement this? It would be great to be able to just use @synthesize to set this up. I could just declare the property as NSMutableArray and @synthesize that, but that doesn't allow me to enforce what types of objects can be placed into the collection, nor does it prevent the client code from modifying the array. What I typically do is something like this:

@property(nonatomic, readonly) NSArray *widgets;

- (void)addWidget:(Widget*)widget;
- (void)removeWidget:(Widget*)widget;
...

The collection is implemented as an NSMutableArray, with an NSArray containing the current contents passed back to the caller. This seems like a lot of coding for what must be a common scenario. Even more coding needs to be done in order to set up key-value observing.

Am I missing something, or is it really this much to work to set up a collection property?

like image 918
brentopolis Avatar asked Nov 13 '22 20:11

brentopolis


1 Answers

You can prevent client code from modifying your array by declaring the property as an NSArray, but using an NSMutableArray as the storage mechanism. The @property and @synthesize directives will still work.

There isn't really a good way to ensure type-safety of the objects returned by your array, but Objective-C programmers almost never worry about that. Its just not a common concern. If you really want to ensure that only objects of a certain type go into and come out of your array, you're going to have to write a wrapper class for NSArray to do so.

like image 62
Ryan Avatar answered Mar 16 '23 18:03

Ryan