main()中的EXC_BAD_ACCESS

Rec*_*Hou 2 cocoa objective-c ios

我有一个EXC_BAD_ACCESSmain(),这里是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

该计划停在main():

int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
Run Code Online (Sandbox Code Playgroud)

正如评论所说,在评论之后[array1 autorelease];,一切都很好.

所以这是我的问题:

  1. EXC_BAD_ACCESS经常表示使用已经发布的对象.显然这与某些事情有关[array1 autorelease];,但我无法理解他们的关系.

  2. 为什么停在这个位置main()- 而不是在其他地方?

新手问题:)

Kri*_*ass 5

arrayWithObject:返回您不拥有的对象.因此,您随后发送它是错误的autorelease.

请参阅基本内存管理规则,具体如下:

  • 您不得放弃您不拥有的对象的所有权

  • 您拥有自己创建的任何对象

您创建使用名称以"黄金"的方法的对象,"新","复制",或"mutableCopy"(例如alloc,newObjectmutableCopy).

另外,作为更一般的观点,请勿使用retainCount.除非您碰巧正在对运行时或其他东西进行低级别的黑客攻击,否则您不需要它,并且它不会向您返回任何有用的东西.

  • 如果你知道它是如何工作的,你知道你在浪费时间使用retainCount,因为有一种更好的方法需要更少或没有代码.... (2认同)