get values form NSMutableArray from end to start - iphone

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

Related

count number of dictionaries within a dictionary

my questions is about iPhone development.
I'm trying to figure out if there is a way to count ONLY the number of dictionaries within a dictionary.
for example, let's say this is my dictionary
Dictionary contains 5 elements:
string
string
NSDictionary
NSDictionary
NSDictionary
I would like to count only the NSDictionaries... so the return value should be 3.
Is there any way to accomplish this?
Thanks.
NSSet *dictKeys = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
return [obj isKindOfClass:[NSDictionary class]];
}];
NSUInteger numberOfDicts = [dictKeys count];
NSDictionary* root = ...;
__block NSUInteger count = 0;
[root enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL* stop) {
if ( [obj isKindOfClass: NSDictionary.class] ) ++ count;
*stop = NO;
}];
Of course
NSUInteger count = 0;
for (id obj in root) {
if ( [obj isKindOfClass: NSDictionary.class] ) ++ count;
}
will work as well.
__block NSInteger countOfDictionaries = 0;
[dictionary enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block {
if ([obj isKindOfClass:[NSDictionary class]]) {
countOfDictionaries++;
}
}];
As shown above, simply enumerate through every object of your dictionary and keep a count of every object that is an "NSDictionary", by testing the class of the object.
Loop through your NSDictionary by using NSEnumrator and do the following test :
if ([myObject class] == [NSDictionary class]) c++;

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 get indices of NSArray using something like indexOfObject?

I can use [NSArray indexOfObject: NSString] to get an index of my search for 1 item. But what can I use or do to get an array of returned indices from my search?
thanks
To get multiple indices, you can use indexesOfObjectsPassingTest::
// a single element to search for
id target;
// multiple elements to search for
NSArray *targets;
...
// every index of the repeating element 'target'
NSIndexSet *targetIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [obj isEqual:target];
}];
// every index of every element of 'targets'
NSIndexSet *targetsIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [targets containsObject:obj];
}];
Support for blocks were added in iOS 4. If you need to support earlier versions of iOS, indexesOfObjectsPassingTest: isn't an option. Instead, you can use indexOfObject:inRange: to roll your own method:
#interface NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target;
#end
#implementation NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target {
NSRange range = NSMakeRange(0, [self count]);
NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
NSUInteger idx;
while (range.length && NSNotFound != (idx = [self indexOfObject:target inRange:range])) {
[indexes addIndex: idx];
range.length -= idx + 1 - range.location;
range.location = idx + 1;
}
return [indexes autorelease];
}
#end
If you don't have access to indexOfObjectsPassingTest, as #outis recommends, you could use indexOfObject:inRange: and loop over the results, updating the range to start after the last result finished, and updating the results into your own NSIndexSet, or NSMutableArray, etc.

Accessing NSDictionary inside NSArray

I have an NSArray of NSDictionary.
Each dictionary in the array has three keys: 'Name', 'Sex' and 'Age'
How can I find the index in NSArray of NSDictionary where, for example, Name = 'Roger'?
On iOS 4.0 and up you can do the following:
- (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
{
return [array indexOfObjectPassingTest:
^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
return [[dictionary objectForKey: #"Name"] isEqualToString: name];
}];
}
Elegant, no?
NSUInteger count = [array count];
for (NSUInteger index = 0; index < count; index++)
{
if ([[[array objectAtIndex: index] objectForKey: #"Name"] isEqualToString: #"Roger"])
{
return index;
}
}
return NSNotFound;
If you're using iOS > 3.0 you will be able to use the for in construct.
for(NSDictionary *dict in myArray) {
if([[dict objectForKey:#"Name"] isEqualToString:#"Roger"]) {
return [myArray indexForObject:dict];
}
}
There's method [NSArray indexOfObjectPassingTest]. But it employs blocks, an Apple extension to C, and therefore is evil. Instead, do this:
NSArray *a; //Comes from somewhere...
int i;
for(i=0;i<a.count;i++)
if([[[a objectAtIndex:i] objectForKey: #"Name"] compare: #"Roger"] == 0)
return i; //That's the index you're looking for
return -1; //Not found

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