简体   繁体   中英

Objective C Get Dictionary from Array[i]

I have an array of dictionaries that populate a tableView as seen below

self.tableCell.usernameLabel.text = [self.loadTableArrayCopy[indexPath.row] valueForKeyPath:@"user.full_name"];

If the user likes the content of the row, they can press a save button on the cell and certain values from the dictionary are saved in Core Data.

The problem: not all values from the dictionary correspond to outlets in the uitableviewcell. If that were not the case, I could do something like this

savedItem.username = self.tableCell.usernameLabel.text

But since some values, such as thumbnails, are not displayed in the cell, I am not sure that I could do something like this since it's not associated with a cell

savedItem.thumbnail = self.thumbnail

My preferred option is to take the indexPath.row, access the dictionary at array[indexPath.row] and save by setting the managed object's properties from the dictionary. How can I get this dictionary out of the array and into a local variable so I can do something like this?

savedItem.thumbnail = [myLocalDictionary valueForKeyPath@"thumbnail"];

If you have single section, you can do it easily:

in cellForRowAtIndexPath set this:

cell.saveButton.tag = indexPath.row;

From save button event do this:

-(void)savePressed:(id)sender{
    UIButton *btn = (UIButton *)sender;
    int row = btn.tag; // This is your selected row.
    NSDictionary *youDictionary = [array objectAtIndex:row];

}

When user tap save button then you could get the indexPath.row value.So later,

NSDictionary *saveDict = [array objectAtIndex:indexPath.row];

This way to will get dictionary and could further save it to coreData.

If not able to find indexPath.row value from button then you could do as below:-

-(void)buttonTapped:(id)sender
{
  UIButton *senderBtn = (UIButton *)sender;
  UITableViewCell *cell;

  if (![Utilities isIPhone]) {
     if ([UIDevice currentDevice].systemVersion.intValue < 7)
        cell = (UITableViewCell *)[[[senderBtn superview] superview] superview];
     else
        cell = (UITableViewCell *)[[[[senderBtn superview] superview] superview] superview];
  }
  NSIndexPath *index =  [advancedSearchTable indexPathForCell:cell];
}

When save is tapped you could add above lines and find out index(indexPath). Later, use index to get dictionary from array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM