views:

221

answers:

2

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];
+1  A: 

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.

Jed Smith
Thanks. But what could be a problem with doing it with stringWithString (even in the worst-case situation)?
z s
I could foresee a weird retain count error, since you're dealing with quite a few allocations there -- only quirk I see, honestly, the rest of the code looks fine (hence my answer). There's symbols in this snippet that are declared elsewhere, and without a definite *this is the line* that's all I've got.
Jed Smith
From my testing, it's pretty obvious to me that this IS the problem line. But I just don't understand exactly why, and hence, I'm not sure what the best solution is. The users who have this issue repeatedly freeze at this point, while I'm looping through their address book. If it was some weird retain count problem, would it be a recurring problem for the same person, even after rebooting their iPhone?
z s
+3  A: 

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].

Jon Hess