0

Hi I have NSarray values in Xcode. I need to get array indexOfObject by comparing string values. my array values are

 (
    {
    firstName = lord;
    lastname = krishna;
    },
    {
    firstName = priya;
    lastname = amirtha;
    }
 )

If I type first name in textfield and click button means last name want to display in another textfield.
thank you.

2
  • 2
    What did you try so far? What did it do wrong? Commented Mar 6, 2014 at 13:09
  • There is this neat invention called a for loop. It really works!! You should try it some time. Commented Mar 6, 2014 at 13:15

2 Answers 2

2

To answer the title of your question:

NSString *compareString = @"something";
NSMutableArray *indexesOfMatches = [[NSMutableArray alloc]init];

for (NSString *string in theArray) {

   if ([string isEqualToString:compareString]) {
       NSNumber *index = [[NSNumber numberWithInterger:[theArray indexOfObject:string]];
       [indexOfMatches addObject:index];
    }
}
    //indexOfMatches will now contain NSNumber objects that represent the indexes of each of the matching string objects in the array

I think that using an NSDictionary would be better for you though. Then you can simply keep the first and last names as Key Value pairs.

NSDictionary *names = @{@"lord" : @"krishna", @"priya" : @"amirtha" };

Then you can just do value for key when you get the first name:

NSString *firstName = @"lord";
NSString *lastName = [names valueForKey:firstName];
Sign up to request clarification or add additional context in comments.

Comments

0

Store firstNameArray and lastNameArray a mutable array NSMutableArray.

Using Fast Enumeration. Suppose array is the array you are provided with

for (NSDictionary *item in array) {
        [firstNameArray addObject:[item objectForKey:@"firstName"]];
        [lastNameArray addObject:[item objectForKey:@"lastName"]];
    }

After entering the data in firstNameTextField click the button

Button action method implementation

-(IBAction)btnClicked:(id)sender {
  NSInteger index = [firstName indexOfObject:[firstNameTextField text]];
  [lastNameTextField setText:[lastName objectAtIndex:index]];
}

3 Comments

where to get array name.
Edited the answer. please check
Is the answer is what you want?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.