5

Possible Duplicate:
Getting Index of an Object from NSArray?

I have one Array and one string. Array name is "Array1", String name is "String", Now i have this below Values in "Array1".

"array1 = [[NSMutableArray alloc]initWithObjects:@"A",@"b",@"c",@"d",@"e", nil];"

My String value is "A"

Now i want to compare these string and array. And i want to display the Array index value.

How can i do this. Please somebody help me. Thanks in advance.

0

5 Answers 5

15

i'm not sure if this is what you're looking for but maybe:

int index = [array1 indexOfObject:String];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. THen if i get the NUmbers means what can i do? for e.x "array1 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];" And another array values @"1". how can i compare this. Please help me to solve this isse.
sorry, i don't get what exactly you mean. What do you want to compare? strings, arrays or indexes?
14
int i;
for (i = 0; i < [myArray count]; i++) {
  id myArrayElement = [myArray objectAtIndex:i];
...do something useful with myArrayElement
 }`

You can Iterate NSMutableArray and to find the location of particular Object use

 int indexValue = [myArray indexOfObject:yourString];

4 Comments

if i get Numbers means what can i do? (e.x): @"1",@"2", like in array1, and string values is @"1".
Thanks for your reply. THen if i get the NUmbers means what can i do? for e.x "array1 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];" And another array values @"1". how can i compare this. Please help me to solve this isse.
not too much clear i think as you can compare NSString and you can convert it into int.
This is perfectly worked fine in my code
5

Try this,

if([array1 containsObject: yourString])
{
   int index = [array1 indexOfObject:yourString];
}

3 Comments

two querys? I suggest to use NSNotFound on the result for performance reasons!
@JonathanCichon But he wants to compare the string with array elements..
but your containsObject is completly unnecessary, as indexOfObject does all you want.
3

Use

NSString *String=@"A";
NSInteger index = [array1 indexOfObject:String]; 

NOTE : Never use variable name with capital String, it should be string.

Comments

1

Checking

int index = [yourArray indexOfObject:yourObject];

is correct for NSString objects and some other types of objects.

When you have implemented a class on your own and you want to get the index of an object within an array you have to implement the method

- (BOOL)isEqual:(id)anObject

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.