0

I have a mutable array containing some arrays for use in a table view controller. The arrays contain a title and some other information. I want the arrays in the master array to be sorted alphabetically in terms of the title they contain. I have assigned the titles with keys:

NSString *title = @"objectTitle";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_storedTitle.text, title, nil];
NSArray *newArray = @[@"Login", dict, _storedUsername.text, _storedPassword.text];

I store the newArray in my masterArray and try to sort the array thus:

    //sort array alphabetically
    NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"objectTitle" ascending:YES];
    NSArray *sortDescriptors = @[titleDescriptor];
    NSArray *sortedArray = [_masterArray sortedArrayUsingDescriptors:sortDescriptors];

    _masterArray = sortedArray.copy;

This is not working, as i have not specified the index where the titleDescriptor is stored. How do I do this?

When accessing the title at a given index (index) in the master array is done as follows:

     NSLog(@"%@", [[[_masterArray objectAtIndex:index] objectAtIndex:1] objectForKey:@"objectTitle"]);
mttrb
  • 8,297
  • 3
  • 35
  • 57
mort
  • 71
  • 1
  • 6

1 Answers1

1

Modified your code like this:-

NSSortDescriptor *sortedDescriptor =
        [[[NSSortDescriptor alloc]
         initWithKey:@"objecttitle"
         ascending:YES
                selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];

NSArray * descriptors =
[NSArray arrayWithObjects:sortedDescriptor, nil];
  NSArray * sortedArray =
 [array sortedArrayUsingDescriptors:descriptors];

NSlog(@"%@",sortedArray);
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • I have updated the code. It does not seem to make any difference. Crashes at NSArray * sortedArray = [_masterArray sortedArrayUsingDescriptors:descriptors]; – mort Oct 06 '13 at 16:14
  • It means your data is not proper. Please follow this http://stackoverflow.com/questions/1844031/how-to-sort-nsmutablearray-using-sortedarrayusingdescriptors – Hussain Shabbir Oct 06 '13 at 16:29
  • True, I had to setup the array differently. Thank you for posting the link! – mort Oct 07 '13 at 15:56