Objective-C array of floats misbehaving (EXC_BAD_ACCESS)
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, th开发者_开发百科ough I can't seem to find a reason why that's true. Anyone see something I'm missing?
You need to alloc your object!
MyObject *k = [[MyObject alloc] init];
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.
You property definition should read:
@property float* d; // missing the '*'
精彩评论