2

I'd like to create an NSObject subclass that contains a few member vars:

@interface PointMass : NSObject
{
    CGPoint mCurPosition;
    CGPoint mLastPosition;
    CGPoint mAcceleration;
}

-(id) initWithPosition:(CGPoint*) pos;


#import "PointMass.h"

@implementation PointMass

-(id) initWithPosition:(CGPoint*)pos
{
    mCurPosition = *pos;
    mLastPosition = *pos;
    mAcceleration = ccp(0,0);
    return self;
}

@end

And I would like to create a C-style array to hold a bunch of them within a cocos2d class:

// mNumPoint declared in interface, I've set it to 100
PointMass *pointMassList;
pointMassList = malloc(sizeof(PointMass*) * mNumPointMass);

for (int = 0; i < mNumPointMass; i++)
{
    CGPoint point = ccp(100,100);
    PointMass *p = [[PointMass alloc] initWithPosition: &point];
    pointMassList[i] = p;
}

But I get an error

Expected method to write array element not found on object of type 'PointMass *'

Do I need to tell the compiler more about my PointMass Object if I want to store pointers to it in a C array?

I'm basically trying to have a play around with some particle math on iPhone without needing to unpack points from an NSArray constantly if it isn't clear what I'm trying to achieve here.

If I've gone about this in a backwards way I'd love to be corrected - it has been a while since I wrote vanilla C and I'm a little rusty!

1 Answer 1

5

it has been a while since I wrote vanilla C

You should still be able to make the distinction between a pointer-to-T and a pointer-to-pointer-to-T (T being PointMass in this case). You want to store an array of PointMass *, and not an array of PointMass (which you couldn't do anyway). So change the declaration of pointMassList to

PointMass **pointMassList;

and it will work. However, if you're using Objective-C anyway, why don't you simply store the instances into an NSArray?

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

2 Comments

It has also been a while since I've looked in my header file for the issue apparently :-S of course I meant pointer to pointer! Need a coffee! I'm using C indexing primarily because I have multidimensional arrays and haven't found a way to access them in NSArray that is as nice as foo[x][y]
@davbryn NSArray can be indexed just like that when using modern compilers.

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.