get the array index in for statement in objective-c - iphone

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

Related

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");
}

get values form NSMutableArray from end to start

I want to take the values from NSMutableArray but want to read from last index to 1st index
thank you
for (id someObject in [someArray reverseObjectEnumerator])
{
//do your thing
}
2 other options:
Simple for-loop (surely not recommended):
for (int i = [array count]-1; i >= 0; ++i)
id value = [array objectAtIndex: i];
Block-based enumeration:
[array enumerateObjectsWithOptions: NSEnumerationReverse
usingBlock: ^(id obj, NSUInteger idx, BOOL *stop){
//do something
}];
Mark's answer is useful, but this form may be useful when you want to mutate the array:
while ([arr count]) {
id obj = [arr lastObject];
// use obj
[arr removeLastObject];
}

How to check whether data or object already exist in PList, iPhone?

I can add and remove an object or data in PList successfully but I wanna know that the data or an object already exist in PList. my code is
NSUInteger countObjectsFromPList;
countObjectsFromPList = [[mdict allKeys] count];
NSLog(#"objects in PList %d", countObjectsFromPList);
for(int i=0; i <= countLawsFromPList; i++){
NSLog(#"\n\n\n%d\n\n\n", i);
//if([objectName isEqualToString:[[mdict allKeys] objectAtIndex:i]])
if(objectName ==[[mdict allKeys] objectAtIndex:i]){
NSLog(#"Already exists");
//NSLog("String is equal");
}
else {
NSLog(#"Added to Favorites");
}
}
Please any one help me to over come this. thanks
id object = [mdict objectForKey:key];
BOOL exists = (object != nil);
Edit: apparently that wasn't clear enough.
Basically with objectForKey you're just telling the dictionary "could you please give me the object for my key key"? If the object is there for that key, the returning value will be non-nil. Otherwise it will be nil. That's why you check for object != nil in order to know if that object exists in the dictionary for your key. goes to take more coffee
Thanks for all the code answers, but they turned out to not be helpful for me. I corrected my code to be:
mdict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self doccumentspath]];
NSUInteger countObjectsFromPList = [[mdict allKeys] count];
NSLog(#"Objects in PList %d", countObjectsFromPList);
for(int i=0; i < countObjectsFromPList; i++){
NSLog(#"\n\n\n%d\n\n\n", i);
NSLog(#"from viewWillAppear- Object Name- %#", object);
if([object isEqualToString:[[mdict allKeys] objectAtIndex:i]]){
NSLog(#"Already exists");
exists = YES;
NSLog(#"The value of the bool is %#\n", (exists ? #"YES" : #"NO"));
}
}
What I had to do is to remove the = in the for loop. Now it's working fine.

Gather the count of a specific object from NSMutableArray

Hey guys & girls,
Im wondering how I can find the object count of a specific type of object in an array.
For example, i have 6 'clouds' in NSMutableArray at random locations, I also have 4 'dragons' in this NSMutableArray.
How can i gather the integer 6?
I was thinking something along the lines of:
int z = [[SomeClass *clouds in _somearray] count];
Any assistance would be greatly appreciated.
Thnx,
Oliver.
Yet another way is in using blocks:
Class cloadClass = NSClassFromString(#"Cloud");
NSArray *a = /* you array with clouds and dragons */;
NSIndexSet *clouds = [a indexesOfObjectsPassingTest:
^(id obj, NSUInteger idx, BOOL *stop) {
return [obj isKindOfClass:cloadClass];
}];
// now we can count clouds
NSLog(#"%d", [clouds count]);
// but also we now can return our clouds immediately and
NSLog(#"%#", [a objectsAtIndexes:clouds]);
int result = 0;
for (NSObject *object in _somearray) {
if ([object isKindOfClass:[SomeClass class]])
result++;
}
result is the count you are looking for
If you're looking for how many times a specific instance of an object appears, you can do:
NSCountedSet *counts = [NSCountedSet setWithArray:myArrayOfObjects];
NSUInteger count = [counts countForObject:myObject];
Otherwise you'd just have to loop through the array manually and count.

How to get index of an item in an array

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.