views:

23

answers:

1

HI,

Due to formatting issues, I'm converting floats to NSNumber in my iPhone app. Although it generates proper strings it crashes program after releasing the object.

I wrote simple program as console app for Mac OS X and same problem occurs. Can anybody advise how to solve that? Here is the code sample. All 3 messages are written to log and after that EXEC_BAD_ACCESS error occurs...

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *FormattedValueString = [[NSString alloc] init];
    NSString *FormattedValueString1 = [[NSString alloc] init];



    NSNumber *myNumber = [[NSNumber alloc] initWithDouble:100.345];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 

    FormattedValueString = [myNumber stringValue];
    FormattedValueString1 = [numberFormatter stringFromNumber:myNumber];

    NSLog(FormattedValueString);
    NSLog(FormattedValueString1);

    [FormattedValueString release];
    [FormattedValueString1 release];
    [numberFormatter release];
    [myNumber release];

    NSLog(@"Everything OK");

    [pool drain];
    return 0;
}
+4  A: 

FormattedValueString and FormattedValueString1 are both autoreleased and so do not need to be released manually. And you don't need to alloc/init the values at the start of the function; the assignment further down overwrites these values.

Stephen Darlington
s/do not need to/must not/ :)
walkytalky
Thanks for answer!I did so in this sample and it works. But going back to iPhone app and doing same doesn't work. Same problem again. Still thank you for pointing me away from NSNumber. It was NSString that caused problem in this sample app and it seems the same is responsible in problems in iPhone app. If you have any idea left, I would appreciate, of course :)
Mladen Despotovic
I fixed iPhone app as well. And I did it in the way that I stopped releasing NSFormatter and NSNUmber as well. THat can't be good, can it?
Mladen Despotovic
It depends on how you obtained the NSFormatter and NSNumber.
JeremyP
Actually, I found out that NSNUmber is also autorelased, but you have to releaseNSFormatter manually.
Mladen Despotovic