hollow7
hollow7

Reputation: 1506

Memory error when asking for the count of a NSMutableArray instance

arrayOfBookViews = [[NSMutableArray alloc] init];
BookView *book1 = [[BookView alloc] init];
[arrayOfBookViews addObject:book1];
BookView *book2 = [[BookView alloc] init];
[arrayOfBookViews addObject:book2];
NSLog(@"%@",arrayOfBookViews);
NSLog(@"%@",arrayOfBookViews.count);

Running this code gives me: ( "", "" ) which is due to the second last line. The last line then throws me a exc_bad_access memory error. Since the array as well as its objects are properly allocated and initialized, I don't see why asking for the count of the array should give me a memory problem. I'm currently using automatic reference counting in this program with xcode 4.

Please explain why the last line in the code produces a memory error. Thanks.

Upvotes: 0

Views: 77

Answers (3)

JeremyP
JeremyP

Reputation: 86691

Please check the return type of NSArray's -count method. You'll find it is an NSUInteger which is a typedef to unsigned int or unsigned long which is a standard C type. You should be using %u or %lu in the format specifier.

Upvotes: 0

beryllium
beryllium

Reputation: 29767

You trying to print int value. Use %d for this:

NSLog(@"%d",arrayOfBookViews.count);

Upvotes: 0

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

arrayOfBookViews.count returns an NSUInteger. NSUInteger is not an object, its a primitive. The %@ format specifier just calls description on the object passed to it, so you tried to call a method on a primitive which is invalid.

Change the log to NSLog(@"%d",arrayOfBookViews.count); and you'll get your result you wanted.

Upvotes: 2

Related Questions