视图控制器的正确释放取决于您如何定义和分配 viewControllers 数组以及如何填充它。
但是,例如,我有一个属性:
@property (nonatomic, retain) NSMutableArray *array;
我用下面的代码初始化了它(注意NSMutableArray本身的autorelease(因为我使用了为我保留它的访问器方法),以及@987654331的显式release @对象):
- (void)makeArray
{
// create an array, using the accessor method (thus why I'm using an autorelease object)
self.array = [[[NSMutableArray alloc] init] autorelease];
// just add four random objects to the array.
// note, adding them to the array increases their retain count, thus I
// release them to bring the retain count back to +1 ... I could have
// done that via autorelease, too
for (NSInteger i = 1; i < 4; i++)
{
Object *obj = [[Object alloc] initWithString:[NSString stringWithFormat:@"Test %d", i]];
[self.array addObject:obj];
[obj release];
}
}
如果我检查 retainCount 的值,我可以看到所有内容的 retainCount 都是 +1,这是适当的:
- (void)logArray
{
// let's examine the retain counts for the objects in the array
// should be "1" given there are no other strong references anywhere
for (id obj in self.array)
NSLog(@"%s %@ (retainCount = %d)", __FUNCTION__, obj, [obj retainCount]);
// let's also examine the retain count for the array, itself
// this should also be "1"
NSLog(@"%s retainCount = %d", __FUNCTION__, [self.array retainCount]);
}
当我在以下方法中清除它(以及 Object 类在其 dealloc 方法期间执行 NSLog 的事实证实了这一事实)时,它(以及数组的各个对象)被正确释放:
- (void)clearArray
{
// let's use the accessor method to release the array and make sure
// the pointer is nil
self.array = nil;
}