Find a dictionary in ArrayOfDictionaries with a specific keyvalue pair - objective-c

I have an array of dictionaries
for(int i = 0; i < 5; i++) {
NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionary];
[_myDictionary setObject:[NSString stringWithFormat:#"%d",i] forKey:#"id"];
[_myDictionary setObject:label.text #"Name"];
[_myDictionary setObject:label1.text #"Contact"];
[_myDictionary setObject:label2.text #"Gender"];
}
[_myArray addObject:_myDictionary];
Now I want to pick a dictionary from the array whose objectForKey:#"id" is 1 or 2 or something else like there is an sql query Select * from Table where id = 2.
I know this process
int index = [_myArray count];
for(int i = 0; i < 5; i++)
{
NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionaryWithDictionary:[_myArray objectAtIndex:i]];
if([[_myDictionary objectForKey:#"id"] isEqualToString:id])
{
index = i;
return;
}
}
if(index != [_myArray count])
NSLog(#"index found - %i",index);
else
NSLog(#"index not found");
Any help would be appreciated.
Thanks in Advance !!!

Try this, this is by using fast enumeration
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for(dict in _myArray)
{
if([[dict valueForKey:#"id"] isEqualToString:#"1"])
{
return;
}
}

You should use [NSNumber numberWithInteger: i] not a NSString.
Code fore this search should look like this:
NSString *valueToFind = [NSString stringWithFormat:#"%d", intValue]; // [NSNumber numberWithInteger: intValue]
NSInteger index = [_myArray indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
return [valueToFind isEqualToString: [obj objectForKey: #"id"]];
}];
NSDitionary *found = [_myArray objectAtIndex: index];

Related

combine multiple array values into one string value?

I want to combine the array values into one string.
my arrays are like...
array1=[#"fizan",#"nike",#"pogo"];
array2=[#"round",#"rectangle",#"square"];
array3=[#"frame",#"frame",#"frame"];
I need like this...
value1 = fizan round frame
value2 = nike rectangle frame
value3 = pogo square frame
try this:
NSArray *array1= #[#"fizan",#"nike",#"pogo"];
NSArray *array2= #[#"round",#"rectangle",#"square"];
NSArray *array3= #[#"frame",#"frame",#"frame"];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:#[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;
for (int i = 0; i<array1.count; i++) {
a = #"";
for (int j = 0; j<count; j++) {
a = [a isEqualToString: #""] ? [NSString stringWithFormat:#"%#",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:#"%# %#",a,[[array objectAtIndex:j] objectAtIndex:i]];
}
[output addObject:a];
}
for (int i = 0; i < output.count; i++) {
NSLog(#"value %i -> %#",i+1,output[i]);
}
Hope this helps!
UPDATE:
NSArray *array1= #[#"fizan",#"",#"pogo"];
NSArray *array2= #[#"round",#"rectangle",#"square"];
NSArray *array3= #[#"frame",#"frame",#"frame"];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:#[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;
for (int i = 0; i<array1.count; i++) {
a = #"";
for (int j = 0; j<count; j++) {
a = [a isEqualToString: #""] ? [NSString stringWithFormat:#"%#",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:#"%# %#",a,[[array objectAtIndex:j] objectAtIndex:i]];
}
[output addObject:a];
}
for (int i = 0; i < output.count; i++) {
NSLog(#"value %i -> %#",i+1,output[i]);
}
I have tested this code. It works perfect. Check again and reconsider the issue.
Do this
NSArray *array1 = #[#"fizan", #"nike", #"pogo"];
NSString *value = [array1 componentsJoinedByString:#" "];
NSLog(#"value = %#", value);
Output will get like
value = fizan nike pogo
For your case
NSArray *completeArray = #[#[#"fizan",#"nike",#"pogo"], #[#"round",#"rectangle",#"square"], #[#"frame",#"frame",#"frame"]];
NSMutableArray *resultArray = [NSMutableArray array];
unsigned long count = 1;
for (int i = 0; i< count; i++) {
NSMutableArray *listArray = [NSMutableArray array];
for (NSArray *itemArray in completeArray) {
count = MAX(count,itemArray.count);
if (i < itemArray.count) {
[listArray addObject:itemArray[i]];
}
}
[resultArray addObject:listArray];
}
for (NSArray *itemArray in resultArray) {
NSString *value = [itemArray componentsJoinedByString:#" "];
NSLog(#"value = %#", value);
}
output
value = fizan round frame
value = nike rectangle frame
value = pogo square frame

Shuffle Two NSMutableArray independently

I'm creating two NSMutableArray in my viewDidLoad, I add it in a NSMutableDictionary. When I tried shuffling it with one array, It is okay. But the problem is when Im shuffling two arrays independently its not working,somehow the indexes got mixed up.
Here is my code for my array (1st Array):
self.items1 = [NSMutableArray new];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"[Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
self.container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"items1"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index1"];
[items1 addObject:container];
}
}
NSLog(#"Count : %d", [items1 count]);
[items1 enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
NSLog(#"%# images at index %d", object, index);
}];
(2nd Array):
self.items2 = [NSMutableArray new];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"secondImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
self.container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"items2"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index2"];
[items2 addObject:container];
}
}
NSLog(#"Count : %d", [items2 count]);
[items2 enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
NSLog(#"%# images at index %d", object, index);
}];
My view for the iCarousel where im using my array:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (carousel == carousel1)
{
NSDictionary *obj = [items1 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:#"items1"]];
view.tag = index;
}
else
{
NSDictionary *obj = [items2 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:#"items2"]];
view.tag = index;
}
return view;
}
then my shuffle code(Which I tried duplicating for the other array,but not working also):
srandom(time(NULL));
NSUInteger count = [items1 count];
for (NSUInteger i = 0; i < count; ++i) {
int nElements = count - i;
int n = (random() % nElements) + i;
[items1 exchangeObjectAtIndex:i withObjectAtIndex:n];
}
How am I going to shuffle it using above code (or if you have other suggestions) with two arrays? Thanks
My other problem is when I tries subclassing the class for the shuffle method or either use the above code, their index mixed. For example:
Object: apple, ball, carrots, dog
Indexes: 1 2 3 4
but in my View when shuffled:
Object: carrots, apple, dog, balle
Indexes: 2 4 1 3
I also have a method, that when the carousel stop, it will delete the image on view.
the cleanest solution: use a Objective-C Category
NSMutableArray+RandomUtils.h
#import <Foundation/Foundation.h>
#interface NSMutableArray (RandomUtils)
-(void)shuffle;
#end
NSMutableArray+RandomUtils.m
#import "NSMutableArray+RandomUtils.h"
#implementation NSMutableArray (RandomUtils)
-(void)shuffle
{
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
NSUInteger nElements = count - i;
NSUInteger n = (arc4random() % nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
#end
import it, wherever you what to shuffle a MSMutableArray
[array1 shuffle];
[array2 shuffle];
I tried to reproduce your mixed indexes problem, but I can't
NSMutableArray *sarray = [NSMutableArray arrayWithArray: #[#"carrots", #"apple", #"dog", #"balle"]];
NSLog(#"%#", sarray);
[sa enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# object at index %lu", obj, idx);
}];
[sarray shuffle];
NSLog(#"%#", sarray);
[sarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# object at index %lu", obj, idx);
}];
results in
(
carrots,
apple,
dog,
balle
)
carrots object at index 0
apple object at index 1
dog object at index 2
balle object at index 3
(
balle,
dog,
carrots,
apple
)
balle object at index 0
dog object at index 1
carrots object at index 2
apple object at index 3
BTW: your example is aslo incorrect: with four objects in an array the indices should start with 0 and maximum is 3. you have 1 and 4.
so array is shuffled and indexes are ok. You must have some other problem in code, that you didn't show.
You should give up your real code.
I am still ot sure, if I understand, what you want. But from your comments I assume, you want to shuffle an array but keep the old indices. This is just not possible, as the index is the position of an object inside an array. But you are always free to save the original index somewhere.
Or you just copy an array, shuffle one of those. Now ho can ask for the index of an object in both arrays.
NSArray *originalArray = #[#"carrots", #"apple", #"dog", #"balle"];
NSLog(#"%#", originalArray);
[originalArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# object at index %lu", obj, idx);
}];
NSArray *shuffledArray = [originalArray arrayShuffled];
NSLog(#"%#", shuffledArray);
[shuffledArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# object at index %lu %lu", obj, idx, [originalArray indexOfObject:obj]);
}];
Assuming the idea is to shuffle two array in the same order then you just need to do the exchange of the 2nd array right after the 1st array?
NSUInteger count = [items1 count];
for (NSUInteger i = 0; i < count; ++i) {
int nElements = count - i;
int n = (random() % nElements) + i;
[items1 exchangeObjectAtIndex:i withObjectAtIndex:n];
[items2 exchangeObjectAtIndex:i withObjectAtIndex:n];
}
Assuming that you have two different array of images which you need to shuffle the images.
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"[Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
//Lazy initialization of dictionary
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"items1"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"index1"];
[items1 addObject:dict];
[dict release];
}
}
add the object to 2nd array in the same way.
NSUInteger count = [items1 count];
for(int i = 0 ;i < count; i++)
{
int nElements = count - i;
int n = (random() % nElements) + i;
[items1 exchangeObjectAtIndex:i withObjectAtIndex:n];
}
second array shuffling
NSUInteger count = [items2 count];
for(int i = 0 ;i < count; i++)
{
int nElements = count - i;
int n = (random() % nElements) + i;
[items2 exchangeObjectAtIndex:i withObjectAtIndex:n];
}
this should work. If you still find the problem let me know.

Get the correct index of dictionary

NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
NSLog(#"The content of array is%#",tmpMutArr);
int index;
for (int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:[NSString stringWithFormat:#"%#", nameString]])
{
index = i;
}
}
}
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
This code is not replacing the matching object in tmpMutArr as I want it to, but replaces all objects in tmpMutArr instead. How to replace only the index I want?
I know that tmpMutArr containing all objects before the replacement, so I just need to specify the index correctly I think. How to do so?
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
NSLog(#"The content of array is%#",tmpMutArr);
int index;
for (int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:nameString])
{
index = i;
break; // << added break
}
}
}
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
maybe, you should try to this version... you have not specified which index is needed, I suppose the first one.
for (int i=0;i<[tmpMutArr count];i++) {
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:[NSString stringWithFormat:#"%#", nameString]]) {
index = i;
break; // when you find the first one, you should go out from the iteration
}
}
}

Displaying an array in xcode

I am trying to display the an array with different factors of a number ("prime"). But instead of giving me the int numbers I always get 0,1,2,3,4,5,... .
factors.text = #"";
int factorsNumber;
NSMutableArray *array;
array = [NSMutableArray arrayWithCapacity:5];
for (factorsNumber=1; factorsNumber<=prime; factorsNumber++) {
if (prime%factorsNumber == 0) {
[array addObject:[NSString stringWithFormat:#"%d", factorsNumber]];
}
}
for (int i = 0; i < [array count]; i++) {
[array replaceObjectAtIndex:1 withObject:#"4"];
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
factors.text = [factors.text stringByAppendingString:temp];
}
Replace
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
with
NSString *temp = [NSString stringWithFormat:#"%d, ", [[array objectAtIndex:i] intValue]];
The problem was you were only printing the array index, not the value.

Extract a NSDictionary from a NSMutableArray

I need to extract a NSDictionary from a NSMutableArray, and extract an object from that dictionary.
The code should be quite easy, but I keep having a SIGABRT error on the NSDictionary declaration.
-(void)calcolaConto {
conto = [[NSNumber alloc] initWithDouble:0];
for (int i=0; [shoppingListItems count]; ++i) {
NSDictionary *dictVar = (NSDictionary *) [shoppingListItems objectAtIndex:i]; //<-- SIGABRT
NSNumber *IO = (NSNumber *) [dictVar objectForKey:#"incout"];
NSNumber *priceValue = (NSNumber *) [dictVar objectForKey:#"price"];
if ([IO isEqualToNumber:[NSNumber numberWithInt:0]]) {
conto = [NSNumber numberWithDouble:([conto doubleValue] + [priceValue doubleValue])];
} else if ([IO isEqualToNumber:[NSNumber numberWithInt:1]]) {
conto = [NSNumber numberWithDouble:([conto doubleValue] - [priceValue doubleValue])];
}
NSLog(#"Valore %#", conto);
}
}
"shoppingListItems" is created in this way:
NSMutableDictionary *rowDict = [[NSMutableDictionary alloc] initWithCapacity:6];
[rowDict setObject:primaryKeyValue forKey: ID];
[rowDict setObject:itemValue forKey: ITEM];
[rowDict setObject:priceValue forKey: PRICE];
[rowDict setObject:groupValue forKey: GROUP_ID];
[rowDict setObject:incOut forKey:INC_OUT];
[rowDict setObject:dateValue forKey: DATE_ADDED];
[shoppingListItems addObject: rowDict];
The problem is that your loop never stops. You should use:
for (NSUInteger i = 0; i < [shoppingListItems count]; i++) {
or:
for (NSDictionary* dictVar in shoppingListItems) {
so that you do not try to access an element that is out of bounds. In your
current loop i will be incremented until it reaches [shoppingListItems count]
which is beyond the end of the array, so objectAtIndex will throw an exception.