1

I've finally pinpointed the exact issue to a problem I've been having, but I'm not sure how to fix it. Here is the general gist of what is happening: I have an array called wordArray, and I am iterating through it. This array can contain strings that are identical to each other and different from one another. All I want to do is retrieve the index of the particular instance that I am currently iterating, so I the simplified version is this:

for(NSString* stringInWordArray in wordArray){
            NSLog(@"String is: %@ Index is: %d",stringInWordArray,[wordArray indexOfObject:stringInWordArray]);
}

This will obviously print out the String, and the index of the string, however, according to the apple documentation, the indexOfObject method "Returns the lowest index whose corresponding array value is equal to a given object." This is a problem for me because if I have an array that looks like this:

["fruit","fruit","panda","happy",nil];

Then this will print:

String is fruit Index is 0
String is fruit Index is 0
String is panda Index is 2
String is happy Index is 3

Where I want the indices to print 0,1,2,3. Any workarounds for this issue?

2 Answers 2

3

Use a "normal" loop:

for (NSUInteger i = 0; i < wordArray.count; i++) {
    NSString *stringInWordArray = wordArray[i];
    NSLog(@"String is: %@ Index is: %u",stringInWordArray, i);
}

Or you can do:

NSUInteger i = 0;
for(NSString* stringInWordArray in wordArray) {
    NSLog(@"String is: %@ Index is: %u",stringInWordArray, i);
    i++;
}

Or you can do:

[wordArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *stringInWordArray = obj;
    NSLog(@"String is: %@ Index is: %u",stringInWordArray, idx);
}];
Sign up to request clarification or add additional context in comments.

3 Comments

wow this seems so obvious now that you say it lol... So caught up with the rest of the problem I couldnt think straight. Thanks!
With the middle option, be careful if you add logic that may use the continue statement. It will skip the increment. Oh, also, with modern compilers you can just use the desired type for the block parameter directly, without a local. I.e. ... enumerateObjectsUsingBlock:^(NSString* stringInWordArray, NSUInteger idx, ...
Would someone care to explain why this was down voted? How is this answer unhelpful or incorrect? No one learns otherwise.
0

You could use a NSDictionary with key = index and the value = your string:

NSDictionary *dict = @{@"0" : @"fruit", @"1" : @"friut", @"2" : @"panda", @"3" : @"happy"};

The keys are unique, so you know which object you use depending on the key.

Comments

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.