NSMutableArray的count方法导致错误的访问错误?

TNT*_*OOL 3 iphone objective-c nslog nsmutablearray ios

我看到一些类似的问题,但没有简单的答案.在我真正使用它们之前,我只是在玩NSMutableArray来感受它们.出于某种原因,当我尝试在数组上调用count时,它给了我一个EXC_BAD_ACCESS错误,我无法找出原因.

    - (void) applicationDidFinishLaunching:(UIApplication*)application 
{   
    // Create window and make key
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [_window makeKeyAndVisible];

    NSMutableArray* test = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:@"first!"], [NSString stringWithFormat:@"second!"], nil];
    [test insertObject:[NSString stringWithFormat:@"inserted"] atIndex:0];
    NSLog(@"%@", [test objectAtIndex:0]);
    NSLog(@"%@", [test objectAtIndex:1]);
    NSLog(@"%@", [test objectAtIndex:2]);
    NSLog(@"%@", [test count]); //bad access here
}
Run Code Online (Sandbox Code Playgroud)

所有插入和访问除了计数方法工作都很好.我不明白为什么这不起作用,非常感谢一些帮助.谢谢!

Joh*_*eek 8

该%@格式说明打印对象.返回值-count只是一个无符号整数.您应该使用该%u类型的格式说明符.

  • @TNTisCOOL:不,一旦你知道崩溃的原因,这并不奇怪.`%@`说明符需要一个对象的*address*,并希望在其上调用`[theObject description]`.当你使用`[test count]`时,你实际上传递了一个像3这样的数字然后被解释为一个地址,但是`3`将是一个无效的地址并试图访问它(取消引用它)会导致崩溃. (4认同)