Cocoa structs and NSMutableArray

岁酱吖の 提交于 2019-12-02 20:34:44

As mentioned, NSValue can wrap a plain struct using +value:withObjCType: or -initWithBytes:objCType::

// add:
[array addObject:[NSValue value:&p withObjCType:@encode(struct Point)]];

// extract:
struct Point p;
[[array objectAtIndex:i] getValue:&p];

See the Number and Value guide for more examples.

You are getting errors because NSMutableArray can only accept references to objects, so you should wrap your structs in a class:

@interface PointClass {
     struct Point p;
}

@property (nonatomic, assign) struct Point p;

This way, you can pass in instances of PointClass.

Edit: As mentioned above and below, NSValue already provides this in a more generic way, so you should go with that.

You could use NSValue, or in some cases it might make sense to use a dictionary instead of a struct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!