我是 Objective-C 的新手。我想使用 NSMutableArray 来存储一些我稍后会访问的对象。
我有界面:
@interface ControlWheel : RotatableObject <LeverSubject>
{
NSMutableArray *subjectArray_;
}
-(id) initWithCWDef: (ControlWheelDef*) def;
-(void) addSubject: (id) subject;
@end
实现如下:
-(id) initWithCWDef:(ControlWheelDef *)def
{
...
self = [super initWithDef:&rDef];
if (self)
{
subjectArray_ = [NSMutableArray arrayWithCapacity:1];
}
return self;
}
-(void) addSubject:(id)subject
{
[subjectArray_ addObject:subject];
}
-(void) angleChangeCallback
{
unsigned int count = [subjectArray_ count];
for (unsigned int i = 0; i < count; i++)
{
[[subjectArray_ objectAtIndex:i] onAngleChanged:angle_];
}
}
问题出在 angleChangeCallback 函数中。 subjectArray_ 超出范围。 我做错了什么?
最佳答案
arrayWithCapacity:
返回一个自动释放的数组。你想要 [[NSMutableArray alloc] init];
。
NSMutableArray
根据需要增长,所以 arrayWithCapacity:
在大多数情况下并不是特别有用,除非你要用已知的大量对象。
哦,它并没有超出范围;它已被自动释放池收集。
关于objective-c - NSMutableArray 超出范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051748/