Bobj-C
Bobj-C

Reputation: 5426

what wrong with NSNumber

i wrote this code :

bs = [NSNumber numberWithFloat:[mystring.text floatValue]];
NSLog(@"bs = %@",bs);

....

float x = [bs floatValue];

when the program want to excute the line above it crash why ?

the output : bs = 2.8 which true 100%

Upvotes: 1

Views: 203

Answers (2)

wingnet
wingnet

Reputation: 138

the code snippet seems ok. and I guess the reason is bs was released before fetching its float value. the simplest way to retain bs is to change it to a property:

@property (nonatomic,retain)NSNumber* bs;

and release it in dealloc

Upvotes: 1

Black Frog
Black Frog

Reputation: 11725

Between the time you assigned an NSNumber object to your ivar bs it was release by the runtime. I am assuming where you created bs and where you try to assign it to x are in two different methods. If that is the case, you need to tell the runtime you want to keep the ivar bs around for awhile:

[bs retain];

And if you do that, you need to tell the runtime you are done in the dealloc:

-(void)dealloc {
    [bs release];
    [super dealloc];
}

Basically, if you didn't create an object with alloc, copy, mutableCopy, new in the method name, then you don't own the object.

Upvotes: 2

Related Questions