Z S
Z S

Reputation: 7511

problem with NSString stringWithString, in iPhone app

This is a snippet of some code that I've been having problems with. I have an iPhone app that works fine for 99% of my users, but for maybe 1%, I have this bug which I can't resolve or reproduce on my end. The app just freezes for them, and doesn't actually crash (so no crash reports). Some ad-hoc distribution testing has revealed the problem to be in this piece of code. If anyone has any ideas of what the problem might be, please let me know. Thanks.

    NSString *addChar = nil; 

    NSString *fullname =  (NSString *)ABRecordCopyCompositeName(record);
    addChar = [[NSString stringWithString: [[fullname substringToIndex:1] capitalizedString]] retain];

    [fname release];

    NSMutableArray *array = [app_contacts objectForKey:addChar]; // lookup if key exists

    if (array == nil) // if nothing in key, create new array
    {
           NSLog(@"array empty"); 
           NSMutableArray *newarray = [[NSMutableArray alloc] init];
           [newarray insertObject:one_person atIndex:0];
           [app_contacts setValue:newarray forKey:addChar];
           [newarray release];
    }
    else
    {
           NSLog(@"array not empty");
           [array addObject:one_person];
           [app_contacts setValue:array forKey:addChar];
    }

    [addChar release];

Upvotes: 0

Views: 993

Answers (2)

Jon Hess
Jon Hess

Reputation: 14247

In this code:

NSString *fullname =  (NSString *)ABRecordCopyCompositeName(record);
addChar = [[NSString stringWithString: [[fullname substringToIndex:1] capitalizedString]] retain];

If fullname is equal to @"", then you'll raise an exception when you invoke [fullname substringToIndex:1].

Upvotes: 3

Jed Smith
Jed Smith

Reputation: 15934

Why are you doing this?

addChar = [[NSString stringWithString: [[fullname substringToIndex:1] capitalizedString]] retain];

You get back a string already:

addChar = [[fullname substringToIndex:1] capitalizedString];

Eliminates the need for the [addChar release] as well.

Upvotes: 1

Related Questions