繁体   English   中英

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

[英]NSMutableArray's count method causes a bad access error?

我看到一些类似的问题,但没有简单的答案。 在我真正使用它们之前,我只是在玩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
}

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

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

问题是[test count]返回NSUInteger而不是指针(指向NSObject )。 试试这个:

NSLog(@"%u", [test count]);

请注意,使用%d也可以,但%u是首选。

- (NSUInteger)count; 返回NSUInteger

请改用:

NSLog(@"%u", [test count]); //bad access here

count工作得很好。 但它返回一个NSUInteger原语,而不是一个指向NSObject子类的指针。 %@ string格式化程序期望指向一个对象并记录从该对象的-description方法返回的NSString 当传递给它一个NSUInteger NSLog假定它是一个对象的指针和忠实地试图发送-description消息给存储器地址3引起该EXEC_BAD_ACCESS。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM