开发者

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 开发者_如何学Pythonbe 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜