views:

177

answers:

3

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);
}
+2  A: 

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

@implementation PointClass {
     struct Point p;
}

@property (nonatomic, assign) struct Point p;

This way, you can pass in instances of PointClass.

Chris Cooper
NSValue provides the functionality you need already.
JeremyP
+2  A: 

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

JWWalker
+3  A: 

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.

Georg Fritzsche