0

Using other answers in this forum I made this class method to tell if a string is a number. It works OK but do I have to alloc-init every time it is called? After all if this was not XCode4 that would constitute a memory leak wouldn't it? NB, I am using XCode4 which has the Automatic Reference Counter which will prevent that happening.

I was hoping to do something like

if this is not alloc-initted then alloc-init 

but can't seem to get it to work.

Method as it stands currently

+ (BOOL)isThisANumber:(NSString *)candidate{

NSNumberFormatter *fmtr = [[NSNumberFormatter alloc] init];
[fmtr setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [fmtr numberFromString:candidate];
if ( myNumber== nil) {
    return NO;
    } 
else{
    return YES;
    }
nerak99
  • 640
  • 8
  • 26

1 Answers1

0

If thread-safety is not an issue, you can always do something like this:

static NSNumberFormatter *fmtr;
if (fmtr==nil)
{
    fmtr=[[NSNumberFormatter alloc] init];
    [fmtr setNumberStyle:NSNumberFormatterDecimalStyle];
}
NSNumber *myNumber = [fmtr numberFromString:candidate];
if ( myNumber== nil) {
    return NO;
} 
else{
    return YES;
}

And btw, your original code leaks memory :-) It allocates a new formatter every time it's called, and never releases it.

Christian Stieber
  • 9,954
  • 24
  • 23
  • I have editted a clarifiy into the Original. As this is XCode4 then I think the memory leak would be handled by ARC and you can't do releases if you have ARC turned on. I understand that a static would mean that their would only be one fmtr which is what I want but I should be able – nerak99 Aug 28 '12 at 13:03
  • As I said in my question prior to the edit, I have tried the if route and can't see why it won't work. I will have another go. – nerak99 Aug 28 '12 at 13:05
  • I don't know a thing about ARC; maybe you'll have to somehow prevent it from releasing the static. – Christian Stieber Aug 28 '12 at 13:22