开发者

NSMutableArray's count method causes a bad access error?

I see a few similar questions, but no simple answers. I'm just playing around with NSMutableArray's to get a feel for them before I actually use them in my real project. Fo开发者_如何学JAVAr some reason, it's giving me an EXC_BAD_ACCESS error when I try to call count on the array, and I can't figure out why.

    - (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
}

All the inserting and accessing EXCEPT the count method work just fine. I don't see why this isn't working, and would greatly appreciate some help. Thanks!


The %@ format specifier prints objects. The return value of -count is just an unsigned integer. You should use the format specifier %u for that type.


The problem is that [test count] returns an NSUInteger not a pointer (to an NSObject). Try this instead:

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

Note that using %d also works, but %u is preferred.


- (NSUInteger)count; returns an NSUInteger.

Use this instead:

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


count is working just fine. It does however return a NSUInteger primitive and not a pointer to a NSObject subclass. The %@ string formatter expects a point to an object and logs the NSString returned from that object's -description method. When you pass it a NSUInteger NSLog assumes it to be an object pointer and dutifully tries to send a -description message to memory address 3 which causes that EXEC_BAD_ACCESS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜