【发布时间】:2012-03-31 11:15:19
【问题描述】:
我在main() 中有一个EXC_BAD_ACCESS,这是我的代码:
int main(int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
[pool release];
return retVal;
}
@interface TestBedAppDelegate : NSObject <UIApplicationDelegate>
@end
@implementation TestBedAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application {
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[TestBedViewController alloc] init]];
[window addSubview:nav.view];
[window makeKeyAndVisible];
}
@end
- (void) action: (id) sender
{
[self highRetainCount];
}
@implementation TestBedViewController
- (void) highRetainCount
{
UIView *view = [[[UIView alloc] init] autorelease];
printf("Count: %d\n", [view retainCount]);
NSArray *array1 = [NSArray arrayWithObject:view];
printf("Count: %d\n", [view retainCount]);
[array1 autorelease]; // If comment this line, everything will be OK
}
@end
程序停在main():
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
正如评论所说,注释掉[array1 autorelease];后,一切正常。
所以这是我的问题:
EXC_BAD_ACCESS通常表示使用已释放的对象。显然和[array1 autorelease];有关系,但我无法理解他们的关系。为什么停在这个位置——
main()——而不是其他地方?
新手问题:)
【问题讨论】:
-
array1已经自动释放,因此调用autorelease会让一切都崩溃。 -
Saphrosit 是对的,你不需要调用 [array1 autorelease];
-
它不是“已经自动发布”,它不属于调用者。有区别(尽管对于外部观察者来说,两者可能看起来相似)。
-
@HotLicks - 不,确实没有,请阅读我的答案中的文档链接。它返回调用者不拥有的
NSArray*。可能是实现创建了一个NSArray,自动释放它并返回它,但也可能实现只是返回一个指向现有实例的指针。 API 指定的只是缺乏所有权;您正在就实施提出声明。 -
@HotLicks 当现有实例由被调用者拥有时,请参见内部记忆
标签: objective-c ios cocoa