How to get index of an item in an array - iphone

I am having array called stored and I want to access their indexes so that I can select them individually to do my operations.
If I want to print their indexes, what should I do?

use NSArray's indexOfObject: method. Such as the following:
NSUInteger fooIndex = [someArray indexOfObject: someObject];

int totalElements = [anArray count];
for(int i=0; i < totalElements; i++)
{
data = [myArray indexOfObject:i];
}
The above code will give you the data if you pass in the index
NSString *haystackText = #"Hello World";
int totalElements = [anArray count];
for(int i=0; i < totalElements; i++)
{
BOOL result = [haystackText caseInsensitiveCompare:[myArray objectAtIndex:i] == NSOrderedSame;
if(result)
{
NSUInteger fooIndex = [myArray indexOfObject: haystackText];
return fooIndex;
}
}
The code above will first find the element in the array and if it exists then return the index.

[array indexOfObject:object]
returns index of "object"

You can use indexOfObject method to get the index of element.
for example
This will give you index of your object
NSInteger index = [yourArray indexOfObject:objectName];
This worked for me. Hope this helps.

You can get a list of the indexes by using the count method which returns the number of elements in the array:
int numElements = [myArray count];
I'll leave it as an exercise to print out the actual index values :)

This article has some great examples of how to iterate over an array. Then, inside the loop, you can use NSLog to print the index.

Related

Fastest way to compare/set strings

I have an array of Place objects. Each Place object has a name and code property, both strings. Each Place object already has a code, but I need to look up the name property from a server. I get back 2 arrays: one contains name, the other codes. These arrays are ordered so that the name at some index in the nameArray corresponds exactly with the code at the same index of the codeArray.
I have been looping through the array of Place objects, then checking to see if the code property for that Place is the same as the current index in the codeArray. If it is, I set the name of that Place by using the same index in the nameArray:
for(int i = 0; i < [placesArray count]; i++)
{
for(int j = 0; j < [codeArray count]; j++) {
if([[[placesArray objectAtIndex:i] code] isEqualToString:[codeArray objectAtIndex:j]]) {
[[placesArray objectAtIndex:i] setName:[nameArray objectAtIndex:j]];
}
}
}
This works but isn't terribly fast - it can take 30 seconds with 1000+ Places to loop through.
Is there a faster way?
As with anytime you're trying to optimize performance, you should profile the code using Instruments to find out where the bottleneck actually is. That said, looping through the placesArray for each name in the nameArray and doing a string comparison is pretty inefficient.
How about something like this?
NSMutableDictionary *placesByCode = [NSMutableDictionary dictionaryWithCapacity:[placesArray count]];
for (Place *aPlace in placesArray) {
[dictionary setObject:aPlace forKey:aPlace.code];
}
NSMutableDictionary *namesByCode = [NSMutableDictionary dictionaryWithCapacity:[namesArray count]];
for (int i=0; i<[namesArray count]; i++) {
NSString *name = [namesArray objectAtIndex:i];
NSString *code = [codeArray objectAtIndex:i];
[namesByCode setObject:name forKey:code];
}
for (NSString *code in namesByCode) {
Place *place = [placesByCode objectForKey:code];
place.name = [namesByCode objectForKey:namesByCode];
}
Looking up each place by its code in the dictionary should be quite a bit faster than manually looping through the whole place array for each name.
You can use for NSArray -containsObject
if ([myarray containsObject:myObject]) {
// ...
}
Try using a break statement in the inner loop. This way you don't need to loop through the entire loop each time.
for(int i = 0; i < [placesArray count]; i++)
{
for(int j = 0; j < [codeArray count]; j++) {
if([[[placesArray objectAtIndex:i] code] isEqualToString:[codeArray objectAtIndex:j]]) {
[[placesArray objectAtIndex:i] setName:[nameArray objectAtIndex:j]];
break;
}
}
}
You could also make the second array become smaller as you find more results. It will cost you more memory but 1000 strings isn't much anyway.
NSMutableArray * tempCodeArray = [NSMutableArray arrayWithArray:codeArray];
for(int i = 0; i < [placesArray count]; i++)
{
for(int j = 0; j < [tempCodeArray count]; j++) {
if([[[placesArray objectAtIndex:i] code] isEqualToString:[tempCodeArray objectAtIndex:j]]) {
[[placesArray objectAtIndex:i] setName:[nameArray objectAtIndex:j]];
[tempCodeArray removeObjectAtIndex:j];
break;
}
}
}
The problem was not the counting for the array, it's the embedded for loop which will take O(n*n) and in Andrew's solution, it's only O(n)+O(n)+O(n)+whatever take to find a object of the key in the dictionary, which i guess would be in a hash table lookup and that's really fast.
Colby, you probably will be ok with Andrew's solution. If you still wanna improve the performance, then a good idea would be sort the array's first then do lookup.
Hope this helps.

How to get index in an NSArray?

NSMutableArray*array = [[NSMutableArray alloc]init];
NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
In the above array 1st Object,2ndObject,3rd Object,4th object,5th Object having val,content,conclusion in each index.
for(int i=0;i<[Somearray count];i++)
{
______________
Here the code is there to give each index ,that is having val,content,conclusion ..
After that val,content,conclusion in each index will be add to Dict..
____________
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:val,#"val",content,#"content",conclusion,#"conclusion",nil];
//Each time adding dictionary into array;
[array addObject:Dict];
}
The above Dictionary is in for loop and the keyvalue pairs will be add 5 times(Somearray Count).Now array is having in
array = [{val="1.1 this is first one",content="This is the content of 0th index",conclusion="this is the conclusion of 0th index"},{val="1.2 this is first one",content="This is the content of 1st index",conclusion="this is the conclusion of 1st index"},____,____,______,{val="1.5 this is first one",content="This is the content of 4th index",conclusion="this is the conclusion of 4th index"},nil];
Now i am having NSString*string = #"1.5";
Now i need the index where val is having 1.5 in it.How to send the str in to array to find the the index.
Can anyone share the code please.
Thanks in advance.
Use method indexOfObject
int inx= [array indexOfObject:#"1.5"];
For Find index particular key value.
int inx;
for (int i=0; i<[array count]; i++) {
if ([[[array objectAtIndex:i] allKeys] containsObject:#"val"]) {
inx=i;
break;
}
}
The method you are looking for is -[NSArray indexOfObjectPassingTest:]. You would use it like this:
NSUInteger i = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [[id objectForKey:#"val"] rangeOfString:#"1.5"].location != NSNotFound;
}];
If you just want to check that val starts with "1.5" you would use hasPrefix: instead.
Try this -
NSArray *valArray = [array valueForKey:#"val"];
int index = [valArray indexOfObject:#"1.5"];
Appended answer given by Mandeep, to show you the magic of key value coding ;)
NSUInteger idx = UINT_MAX;
NSCharacterSet* spaceSet = [NSCharacterSet whitespaceCharacterSet];
for(int i=0,i_l=[Yourarray count];i<i_l;i++) {
NSString* s_prime = [[Yourarray objectAtIndex:i] valueForKey:#"val"];
if ([s_prime length] < 4) {
continue;
}
NSString *subString = [[s_prime substringToIndex:4] stringByTrimmingCharactersInSet:spaceSet];
// NSLog(#"index %#",s);
if ([subString isEqualToString:secretNumber]){
idx = i;
break;
}
}
if (idx != UINT_MAX) {
// NSLog(#"Found at index: %d",idx);
} else {
// NSLog(#"Not found");
}

How to determine the index number of the last object in a NSMutable Array

I have a NSMutable Array and was trying to find the index number of the last object in this array. I tried this, but it feels cumbersome:
int currentCount = [[[self.myLibrary objectAtIndex:currentNoteBookNumber] tabColours] count];
NSLog(#"Number of tab colours total: %i", currentCount);
NSLog(#"Index number of last object: %i", currentCount-1);
Is there another way of doing this? The context of my problem is that I need to determine the last object in order to change it:
replaceObjectAtIndex:[last object] withObject: ...
Thanks!
If you need the index, then that is the way to do it (int lastIndex = [array count] - 1;). If you just want to replace the last object with a different object however, you can do:
[array removeLastObject];
[array addObject: newLastObject];
Try this:
[myArray replaceObjectAtIndex:[myArray count]-1 withObject:someNewObject];
If you add objects to your NSMutableArray with addObjects: method it always put elements at the end. When you removeObjectAtIndex:index it automatically shift down on 1 position all elements with indexes > index. That is why the last object in array is always have index [array count] - 1. I do not tell you about replacing objects, I just tell about adding objects.
int index=[*yourarrayname* indexOfObject:[*yourarrayname* lastObject]];
NSLog(#"index=%d",index);
Use this snippet:
int lastIndex = [YOUR_ARRAY count] - 1;
this will gives you last index of your array.

get the array index in for statement in objective-c

I am stuck in a stupid mess...
I want to get not only the value of an array but also the index of the values.
In PHP it's simple: foreach($array as $key->$value) Here $key will contain the index value.
Isn't there a similar approach in objective c?
How else could I achieve this?
Please help! :((
Arrays not like in php are numbered 0-size of array. I guess you talking about dictionary's. If so you can get array of key with [dict allKeys].
so something like this should work:
for(id key in [dict allKeys]){
id value = [dict objectForKey:key];
}
If you're on iOS4 you can do
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSLog(#"%# is at index %u", obj, idx);
}];
on iOS 3.x you can do
NSUInteger idx = 0;
for (id obj in array)
{
NSLog(#"%# is at index %u", obj, idx);
idx++
}
for (i=0;i<array.count;i++)
{
NSLog(#"Index=%d , Value=%#",i,[array objectAtIndex:i]);
}
Use this its simpler...
hAPPY cODING...
I'm unable to test it, but I think I did do something similar the other night. From this wiki it looks like you can do something like
for(id key in d) {
NSObject *obj = [d objectForKey:key]; // We use the (unique) key to access the (possibly non-unique) object.
NSLog(#"%#", obj);
}
int arraySize = array.count;
// No need to calculate count/size always
for (int i=0; i<arraySize; i++)
{
NSLog(#"Index=%d , Value=%#",i,[array objectAtIndex:i]);
}

NSMutable Array

I have a NSMutableArray:
NSMutableArray *temp = //get list from somewhere.
Now there is one method objectAtIndex which returns the object at specified index.
What I want to do is that, I want to first check whether an object at specified index exists or not. If it exists than I want to fetch that object. Something like:
if ([temp objectAtIndex:2] != nil)
{
//fetch the object
}
But I get exception at the if statement saying that index beyond bound.
Please anyone tell me how to achieve this.
you cannot have 'empty' slots in an NSArray. If [myArray count]==2 ie array has two elements then you know for sure that there is an object at index 0 and an object at index 1. This is always the case.
Check the length first using the count method.
if ([temp count] > indexIWantToFetch)
id object = [temp objectAtIndex:indexIWantToFetch];
you could do this way:
When you initialize, do something like:
NSMutableArray *YourObjectArray = [[NSMutableArray alloc] init];
for(int index = 0; index < desiredLength; index++)
{
[YourObjectArray addObject:[NSNull null]];
}
Then when you want to add but check if it already exists, do something like this:
YourObject *object = [YourObjectArray objectAtIndex:index];
if ((NSNull *) object == [NSNull null])
{
/// TODO get your object here..
[YourObjectArray replaceObjectAtIndex:index withObject:object];
}
Just check that the index is >= 0 and < count
Returns the number of objects currently in the receiver.
- (NSUInteger)count
int arrayEntryCount = [temp count];
First of all you check the length of array-
NSMutableArray *temp = //get list from somewhere.
now check-
if(temp length)
{
Your objectclass *obj = [temp objectAtIndex:indexnumber];
// indexnumber is 0,1,2 ,3 or anyone...
}