Fernando
Fernando

Reputation: 241

Multiple Nib files in UITableView

I am currently retrieving objects from Parse.com and saving them to CoreData.

I am then next using NSFetchedResultsController to retrieve objects from CoreData. These objects will then be used to create a table view. Everything i retrieve from CoreData is stored in an NSArray using the following code:

NSArray *fetchedObjects = _fetchedResultsController.fetchedObjects;

Using the fetched objects array i am wanting to load a specific nib file depending on the type of each object. So using the following for loop within cellForRowAtIndexPath i am trying to achieve this:

for (NSManagedObject *o in fetchedObjects)
{
    if ([[o valueForKey:@"type"] isEqual: @"Type1"])
    {
        Type1CustomCell *cell = (Type1CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"type1CustomCell"];
        return cell;
    }
    else if ([[o valueForKey:@"type"] isEqual: @"Type2"])
    {
        Type2CustomCell *cell = (Type2CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"type2CustomCell"];
        return cell;
    }
} 

The previous code is just an example using 2 types, but within the app there may be more.

The return statement cause the loop to end, which means the loop never gets past the first object. Could someone please give me a point in the right direction of how to load multiple nib files depending on the type of the object I have retrieved?

Thanks

Upvotes: 0

Views: 163

Answers (1)

nhgrif
nhgrif

Reputation: 62072

So, the only time you dequeue and return reusable collection view cells is in the datasource method that asks for a cell.

When this method fires, it's given you a specific index path--the index path for the row it's trying to create.

You don't need to be looping through anything in this method. You just need to go to the right index of whatever collection you're storing your data in, grab the object at that index. Use that data to determine what cell to return.

Instead of a forin loop, just grab a single object.

NSManagedObject *obj = [fetchedObjects objectAtIndex:indexPath.row];

if ([[obj valueForKey:@"type"] isEqual: @"Type1"]) {
    // etc...

You'll still need a large if-else structure here, I believe, but now we're just checking an object at the specific index the table view is trying to create the cell for.

Upvotes: 1

Related Questions