Search code examples
iphonecrashios-simulator

crashed on iphone but not on simulator


It is really mind boggling to find out many differences between the iphone and the simulators. I spent several hours trying to figure out why my application ran on the simulator but crashed on my iphone device. It turns out the culprit is sortedArrayUsingDescriptors. Are there more get-you like this? Please share with me.

To share with you on the issue and the fixes:


Code crashed on iphone but not simulator

NSSortDescriptor* aDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"count" ascending:NO] autorelease];
NSArray* anNsArray = [[NSArray alloc] init];
NSArray* aSortedNsArray = [[NSArray alloc] init];

aSortedNsArray = [anNsArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:aDescriptor]];

The issue is on [NSArray arrayWithObject:aDescriptor];


The fixes are to create an Array to store it:

NSArray* descriptorArray = [[NSArray alloc] initWithObjects:countDescrp, nil];
aSortedNsArray = [anNsArray sortedArrayUsingDescriptors:descriptorArray];

Solution

  • NSSortDescriptor* aDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"count" ascending:NO] autorelease]; 
    NSArray* anNsArray = [[NSArray alloc] init];
    NSArray* aSortedNsArray = [[NSArray alloc] init];
    
    aSortedNsArray = [anNsArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:aDescriptor]];
    

    This is a wrong initialization mechanism, and if the code snippet is complete, your problem lies on the anNsArray object that's empty.

    You also do not need to initialize the aSortedNsArray.

    So it should be:

    NSSortDescriptor* sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"count" ascending:NO] autorelease]; 
    
    // Assume you return it as array of objects from a property or method
    NSArray *array = [self objects]; 
    NSArray *sortedArray = nil;
    if ([array count] > 0) {
         sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    }
    
    // Then you check the sortedArray
    if (sortedArray == nil || [sortedArray count] == 0)
       [self somethingIsWrong];     
    

    arrayWithObject: (autoreleased) or initWithObject: (manual) is just a different way to allocate NSArray object. It won't cause crashes normally. Because what you care about is the sortedArray not retaining the descriptors array object.