[英]Objective-C array of objects misbehaving (EXC_BAD_ACCESS) in TableViewController
[英]Objective-C array of floats misbehaving (EXC_BAD_ACCESS)
我在一个对象上声明了一组原语,并且似乎无法从外部访问它。 我在ObjectiveC还是个新手,我犯了一些明显的错误吗?
头文件:
@interface MyObject : NSObject {
//@public <-- this shouldn't be necessary, right? I have accessors!
float *d;
}
@property float *d;
.m文件:
@synthesize d;
-(id) init {
...
self.d = (float*) malloc(sizeof(float) * n); //n > 1000
...
}
执行访问的位置:
MyObject* k = [MyObject init];
NSLog(@"%f",k.d[0]);
我在最后一行收到了EXC_BAD_ACCESS错误,尽管我似乎找不到真正的原因。 有人看到我想念的东西吗?
您需要分配对象!
MyObject *k = [[MyObject alloc] init];
我编译并运行了以下版本的代码:
@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];
}
正常运行并打印0.00000。 因此,我认为您未向我们显示的代码有问题。
注意,如果我执行k = [FloatClass init]
,则会抛出NSInvalidArgument异常。
注意2.确保init方法返回self。
您的属性定义应为:
@property float* d; // missing the '*'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.