HurkNburkS
HurkNburkS

Reputation: 5510

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.

Upvotes: 1

Views: 8259

Answers (1)

GoZoner
GoZoner

Reputation: 70145

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]);

Upvotes: 6

Related Questions