views:

65

answers:

3

I'm declaring an array of primitives on one of my objects, and cannot seem to access it from the outside. I'm fairly new at ObjectiveC, is there some obvious mistake I'm making?

header file:

@interface MyObject : NSObject {
    //@public <-- this shouldn't be necessary, right? I have accessors!
    float *d;   
}

@property float *d;

.m file:

@synthesize d;

-(id) init {
...
    self.d    = (float*) malloc(sizeof(float) * n); //n > 1000
...
}

location performing the access:

MyObject* k = [MyObject init];

NSLog(@"%f",k.d[0]);

I receive an EXC_BAD_ACCESS error at the last line, though I can't seem to find a reason why that's true. Anyone see something I'm missing?

A: 

You property definition should read:

@property float* d; // missing the '*'
fbrereto
thanks - missed that typo when writing the question. My source has the *, it's not the cause of my grief :(
blueberryfields
+9  A: 

You need to alloc your object!

MyObject *k = [[MyObject alloc] init];
Garrett
This is true, but I can't believe it's the problem. That should crash immediately with a bad argument exception, since classes do not respond to init. If it's getting past there, he must not be showing us the real code.
Chuck
It turns out that there were two errors - the code performing the access was being executed before the initializer, and I was not properly allocating my object.
blueberryfields
+1  A: 

I compiled and ran a version of the code as follows:

@interface FloatClass : NSObject
{
    float* d;
}

@property float* d;

@end

@implementation FloatClass

@synthesize d;

-(id) init
{
    self = [super init];
    if (self != nil)
    {
        d = malloc(sizeof(float) * 10);
    }
    return self;
}

@end

int main(int argc, char *argv[])
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    FloatClass* k = [[FloatClass alloc] init];
    NSLog(@"%f", k.d[0]);

    [pool drain];
}

It ran fine and printed 0.00000. Therefore I reckon there is something wrong with the code you are not showing us.

NB, if I do k = [FloatClass init] I get an NSInvalidArgument exception thrown.

NB 2. Make sure the init method returns self.

JeremyP
Yes, you're correct, that should have been the exception - it was being masked by other components of the system which caused the accessing code to be run before the initializer.
blueberryfields