Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. For 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!

like image 275
TNTisCOOL Avatar asked Dec 08 '25 02:12

TNTisCOOL


2 Answers

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.

like image 59
John Calsbeek Avatar answered Dec 10 '25 17:12

John Calsbeek


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.

like image 38
PengOne Avatar answered Dec 10 '25 16:12

PengOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!