-1

I have a simple UITableView formed from a given NSArray (of NSDictionaries) in reverse order so that newly added cells would appear on top:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [(NSDictionary*)list[list.count - indexPath.row - 1] objectForKey:@"name"];

    return cell;
}

The table can then be manually sorted by user:

https://i.stack.imgur.com/kn8BV.png

My question is how to get the array sorted in the way that the table would keep its new order next time user launches the app.

Hodit
  • 331
  • 2
  • 9
  • 1
    you can try to add indexesin the dictionary which will keep the index value of all the items added. Now you can arrange array according to indexes. – Ashutosh Feb 05 '14 at 12:29
  • look at tableview delegates like `canMoveCellAtIndexPath` – Preetam Jadakar Feb 05 '14 at 12:30
  • @Ashu, that should be added as an answer (with a little more detail about maintaining the dict during a move) – Wain Feb 05 '14 at 12:30

2 Answers2

0

You should save dictionary in local file (i.e. JSON) and load it from stored file when user launch next time. You can take help from this link about saving file in JSON. Generate JSON string from NSDictionary

Community
  • 1
  • 1
GMJigar
  • 496
  • 4
  • 14
  • Make a datasource object. Load table contents from that data source. Reorder objects in datasource array when you reorder table. Then save it in JSON. – GMJigar Feb 05 '14 at 12:34
  • I don't have problems storing datasource on disk. I just don't know how to sort it based on tableView's order. – Hodit Feb 05 '14 at 12:37
  • When you add a new cell in UITableView at some index i, insert that object in dictionary at that index as well. [datasourceDict setObject:item forKey:[NSNumber numberWithInt:i]]; – GMJigar Feb 05 '14 at 12:43
0

I think their is an array of NSdictionary with you and you are loading data in table view from this array. Now what you can do is just add one more object in your dictionary with key say "indexes". Now you can arrange the array in increasing or decreasing order of indexes and then reload your table view as per the requirement. You can use below code for arranging data:

NSSortDescriptor *lowestToHighest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
[yourAray sortUsingDescriptors:[NSMutableArray arrayWithObject:lowestToHighest]];
Ashutosh
  • 2,215
  • 14
  • 27