简体   繁体   中英

get value from NSArray using for loop

I have made an array of NSStrings, which combine two elements of a NSDictionary I have from another original NSArray, I have done this for display/sorting purposes in a UITableView.

Then with the original NSArray, when the user touches a cell and initiates the didSelectCellAtIndexPath function I would like to compaire the cell.textLabel.text to the NSString in modified NSArray, then using the array counter I would like to assign the NSDictionary of the original Array to singleEntryArray.

I have tried myself but I keep getting null returned to the NSDictionary but am not sure why.

for (int i=0; [[modifiedArray objectAtIndex:i] isEqualToString:cell.textLabel.text]; i++) {
                singleEntryArray = [originalArray objectAtIndex:i];
            }

Any help would be greatly appreciated.

The predicate in for needs to be true to continue. For example, typically:

   for (i = 0; i < 10; i++) ...

in your case you probably don't get a true on the first iteration and thus singleEntryArray is unassigned.

Try like this:

  int i = 0;
  for (NSString *obj in modifiedArray)
    if ([obj isEqualToString: cell.textLabel.text])
      break;
    else 
      i++;
  /* Value of 'i' is index into array.  Caution if not found! */
  singleEntryArray = [originalArray objectAtIndex: i];

[edit] As @chuck points out. The above is more conveniently expressed as

int i = [modifiedArray indexOfObject: cell.textLabel.text];
singleEntryArray = (i == NSNotFound ? NULL : [originalArray objectAtIndex: i]);

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