Question

I have a UITableView that adds information from a Core Data the following way:

  1. The "Category" for various names is added at the header
  2. The names that correspond to the Category should be loaded in cells beneath the Category

Right now I have the header loading the right name and the right number of sections and rows being added. However - the results from Core Data are being returned as an NSSet, so I can't add each name to the cells based on the indexPath.row.

Any suggestions? For reference:

cell.textLabel.text = [NSString stringWithFormat:@"%@",[[[dataToUse objectAtIndex:indexPath.section]valueForKey:@"heldBy"]valueForKey:@"name"]];

Returns the appropriate set of names to each cell of the appropriate section, but it returns the ENTIRE set to each cell. I just want each name to be added based on which row it's a part of. I can solve this by converting the NSSet to an Array, but since there are multiple sets being created (because there are multiple categories) I don't see how I can do this.

EDIT: I fixed my problem by doing the following, but I'm still interested to know what the best thing to do would have been.

NSSet *daset = [[dataToUse objectAtIndex:indexPath.section]valueForKey:@"heldBy"];
NSMutableArray *addToLabel = [[NSMutableArray alloc]init];
int i = 0;
for(NSSet *contact in daset) {
    [addToLabel insertObject:[contact valueForKey:@"name"] atIndex:i];
    NSLog(@"%@",addToLabel);
    i++;
}
cell.textLabel.text = [NSString stringWithFormat:@"%@",[addToLabel objectAtIndex:indexPath.row]];
Was it helpful?

Solution

Use an NSFetchedResultsController

It's designed to do exactly what you're looking for. For straight forward cases like yours, where you just need your data organized into sections based on your model relationships it will offload a lot of weight off your shoulders by automatically managing the fetching, editing, caching etc. You can find a nice tutorial here and of course the official documentation here.

OTHER TIPS

To convert from NSSet->NSArray you need to sort the set with a NSSortDescriptior. Something like:

NSSortDescriptor *sort=[[NSSortDescriptor alloc] initWithKey:@"nm" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];

  NSArray *arr = [[myset allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

NSSortDescriptor *sort=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];

NSArray *arr = [[myset allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

"nsset object" *nssetObject =[arr objectAtIndex:indexPath.row];

cell.textLabel.text = [NSString stringWithFormat:@"%@",nssetObject.name];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top