Circle
Circle

Reputation: 165

Cocoa structs and NSMutableArray

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);
}

Upvotes: 16

Views: 7844

Answers (3)

Chris Cooper
Chris Cooper

Reputation: 17564

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.

Upvotes: 3

Georg Fritzsche
Georg Fritzsche

Reputation: 98964

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.

Upvotes: 45

JWWalker
JWWalker

Reputation: 22707

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

Upvotes: 2

Related Questions