I have an NSMutableArray that I'm trying to store and access some structs. How do I do this? 'addObject' gives me an error saying "Incompatible type for argument 1 of addObject". Here is an example ('in' is a NSFileHandle, 'array' is the NSMutableArray):
//Write points
for(int i=0; i<5; i++) {
struct Point p;
buff = [in readDataOfLength:1];
[buff getBytes:&(p.x) length:sizeof(p.x)];
[array addObject:p];
}
//Read points
for(int i=0; i<5; i++) {
struct Point p = [array objectAtIndex:i];
NSLog(@"%i", p.x);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With