Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 529
Circle Avatar asked Jun 01 '10 02:06

Circle


3 Answers

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.

like image 71
Georg Fritzsche Avatar answered Sep 29 '22 16:09

Georg Fritzsche


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.

like image 35
Chris Cooper Avatar answered Sep 29 '22 17:09

Chris Cooper


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

like image 2
JWWalker Avatar answered Sep 29 '22 16:09

JWWalker