我正在开发一个iPhone应用程序。
我有以下INIT代码:
shapes = [NSMutableArray arrayWithCapacity:numShapes];
在此之后,我想做以下几点:
- (CGSize) sizeOfShapeType:(ShapeType)type{
CGSize shapeSize = CGSizeMake(0, 0);
if (shapes != nil) {
for(Object2D* obj in shapes)
if (obj.figure == type) {
shapeSize = obj.size;
break;
}
}
return (shapeSize);
}
但是我总是得到一个EXEC_BAD_ACCESS,因为形状数组中的所有形状都是空的。
如何检查Object2D是否为空?
我有个例外:
for(Object2D* obj in shapes)
发布于 2011-07-03 13:55:19
arrayWithCapacity返回自动释放的对象,因此您必须保留它,以确保它不会过早地被释放:
shapes = [[NSMutableArray alloc] initWithCapacity:numShapes];
或
// .h file
@property (nonatomic, retain) NSMutableArray *shapes;
// .m file
@synthesize shapes;
// your init method
self.shapes = [NSMutableArray arrayWithCapacity:numShapes];
对于后一种解决方案,您需要为shapes声明带有retain属性的属性。
发布于 2011-07-03 13:57:17
获得EXC_BAD_ACCESS的原因可能是您没有声明分配给shapes
变量的对象的所有权,而不是NSMutableArray
的问题。我假设shapes
是一个实例变量。在调用sizeOfShapeType
时,存储在shapes
中的对象已被释放。
因此,解决办法是主张所有权。
shapes = [[NSMutableArray arrayWithCapacity:numShapes] retain];
// or
shapes = [[NSMutableArray alloc] initWithCapacity:numShapes];
发布于 2011-07-03 14:25:47
shapes = [NSMutableArray arrayWithCapacity:numShapes];
您是否实际创建并加载了带有Object2D对象的数组?上面的数组初始化将使用指向对象的指针的numShapes
数的空格初始化数组。但是数组仍然有效地为空。它不会为您创建任何Object2D
对象。
如果我说的是显而易见的话我很抱歉。但是,如果这是您在init代码中所做的全部工作,那么您就误解了arrayWithCapacity:
的含义。
https://stackoverflow.com/questions/6563260
复制相似问题