ele
ele

Reputation: 6181

How to populate a table view contents from two arrays?

I'm looking for a way to populate a table view with images and text from two separate (but parallel) arrays. I've been trying to start with two mutable arrays instantiated with all possible contents, checking against the contents of the model object, removing the "blank" entries, and copying what's left into the table view property that populates the table view cells.

(The person object from which profileList is getting its initial values is the model object being passed in.)

    NSMutableArray *profileList = [@[person.facebook, person.twitter, person.pinterest, person.linkedIn, person.youTube, person.googlePlus, person.flickr] mutableCopy];
    NSMutableArray *buttonList = [@[@"btn-Facebook.png", @"btn-Twittter.png", @"btn-Pinterest.png", @"btn-LinkedIn.png", @"btn-YouTube.png", @"btn-Google+.png", @"btn-Flickr.png"] mutableCopy];
    NSMutableArray *indicesToRemove = [@[] mutableCopy];

    //    for (NSString *index in profileList) {
    //
    //    }
    int i = 0;
    for (NSString *indexContents in profileList) {
        if ([indexContents isEqual: @""]) {
        // [indicesToRemove addObject:[NSString stringWithFormat:@"%d", i]];
            [indicesToRemove addObject:indexContents];
        }
        i++;
    }
    for (NSString *count in indicesToRemove) {
        // [profileList removeObjectAtIndex:[count integerValue]];
        [profileList removeObject:count];
        // [buttonList removeObjectAtIndex:[count integerValue]];
    }

    self.socialMediaProfilesList = (NSArray *)profileList;
    self.socialMediaButtonsList = (NSArray *)buttonList;

This works for profileList but not for buttonList. (Since later, in tableView:cellForRowAtIndexPath:, cell.textLabel.text sets fine but cell.imageView.image throws an exception.)

As you can perhaps tell from the commented-out lines, I tried refactoring this method to track the indexes rather than the contents, but with that I wasn't even able to get the table to load.

It seems like I'm going about this all the wrong way but I can't come up with a better approach. Any ideas?

Upvotes: 0

Views: 171

Answers (1)

fguchelaar
fguchelaar

Reputation: 4909

Ok, pointers :)

  • instead of using fast-enumeration, use a plain for-loop (for (int i=0; i < COUNT; i++))
  • store all indexes in a NSMutableIndexSet
  • use removeObjectsAtIndexes: to clear out all objects, by calling it on both arrays

edit: Or, alternatively, reverse the order of the for-loop ( int=COUNT-1; i >=0; i-- ) and remove the objects from the arrays directly.

Upvotes: 1

Related Questions