16

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

3 Answers 3

45

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know who you are, but I will find you and get you a beer!
3

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.