views:

119

answers:

2

Okay, I know I must be doing something incredibly stupid here. Here's the sample code (which, when executed within a viewDidLoad block silently crashes... no error output to debug console).

NSMutableArray *bs = [NSMutableArray arrayWithCapacity:10];
[bs addObject:[NSNumber numberWithInteger: 2]];
NSLog(@"%@", [bs count]);
[bs release];

What am I missing?

Oh... and in case anyone is wondering, this code is just me trying to figure out why I can't get the count of an NSMutableArray that actually matters somewhere else in the program.

+8  A: 

[mutableArray count] returns a NSUInteger. In your NSLog, you specify a %@, which requires a NSString. Obj-C does not automatically cast integers into strings, so you'll need to use:

NSLog(@"%u", [bs count]); // Uses %u specifier which means unsigned int

Bone up on how to use string formatting. Here's a link:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

You're also releasing an object that already autoreleased. As a rule of thumb, don't ever call release/autorelease on an object, unless you yourself have also done an alloc/retain/copy on it. The majority of the time, objects you get from other class methods have already been autoreleased for you, so you shouldn't do another release.

David Liu
Actually %@ doesn't require NSString, it works for any objective-c object, including NSString.
progrmr
`%@` works for more than just Objective-C objects, it also works for CFTypeRef objects too. For Objective-C objects, the result of sending `description` is used (or `descriptionWithLocale:` if it exists), and for Core Foundation types, it is the result of calling `CFCopyDescription`.
dreamlax
%@ will not work with a NSUInteger, for that's not an object. Per the iPhone OS headers: ----#typedef unsigned int NSUInteger----
Joseph Beckenbach
+5  A: 

Don't release it at the end!

arrayWithCapacity:10 returns an autoreleased object, which means it will get released automatically later. Releasing it yourself means it's count will go to -1 and unhappy things will happen! (As you have discovered)

As a general rule, objects returned by methods containing the words alloc or copy must be released by you, but no others! (Unless, of course, you retain them first)

Chris Cooper