Reputation: 125
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!
Upvotes: 3
Views: 1761
Reputation: 7193
- (NSUInteger)count;
returns an NSUInteger
.
Use this instead:
NSLog(@"%u", [test count]); //bad access here
Upvotes: 1
Reputation: 17958
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.
Upvotes: 0
Reputation: 48398
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.
Upvotes: 2
Reputation: 36497
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.
Upvotes: 8