I have three NSArrays, and I want to combine them all into a single NSDictionary. The problem is that as I iterate through the arrays and create the dictionary, it overwrites the previous object. In the end I only have one object in my dictionary. What am I doing wrong? Here's my code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(int i=0; i<[array0 count]; i++) {
[dict setObject:[array0 objectAtIndex:i]
forKey:#"one"];
[dict setObject:[array1 objectAtIndex:i] f
orKey:#"two"];
[dict setObject:[array2 objectAtIndex:i]
forKey:#"three"];
}
Maybe this will clarify what I mean...
this is the result I'm going for:
{one = array0_obj0, two = array1_obj0, three = array2_obj0},
{one = array0_obj1, two = array1_obj1, three = array2_obj1},
{one = array0_obj2, two = array1_obj2, three = array2_obj2},
etc
Thanks
Issue
You are inserting and replacing the same object at the specific key. So all what dictionary has is its last object at the last index.
Solution
Use this code to add the three arrays into one dictionary with your specific keys.
NSDictionary *yourDictinary = #{#"one": array0, #"two": array1, #"three": array3};
Edit
If you need to add objects of your NSMutableArrays to one NSDictionary you can follow the answer posted by #ElJay, but that's not a good practice, since you are dealing with multiple objects with unique keys.
Update
To do that thing, we are talking about a single NSMutableArray and multiple NSDictinarys.
Follow this code:
NSMutableArray *allObjects = [NSMutableArray new];
for(int i=0; i<[array0 count]; i++) {
dict = #{#"one": array0[i], #"two": array1[i], #"three": array2[i]};
[allObjects addObject:dict];
}
Here ya go:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(int i=0; i<[array0 count]; i++) {
[dict setObject:[array0 objectAtIndex:i] forKey:[NSString stringWithFormat:#"arr0_%d", i]];
[dict setObject:[array1 objectAtIndex:i] forKey:[NSString stringWithFormat:#"arr1_%d", i]];
[dict setObject:[array2 objectAtIndex:i] forKey:[NSString stringWithFormat:#"arr2_%d", i]];
}
Edit - with revised question:
self.array0 = #[#"Array0_0",#"Array0_1",#"Array0_2", #"Array0_3"];
self.array1 = #[#"Array1_0",#"Array1_1",#"Array1_2", #"Array1_3"];
self.array2 = #[#"Array2_0",#"Array2_1",#"Array2_2", #"Array2_3"];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i< [_array0 count]; i++) {
NSDictionary *dict = #{#"one":[_array0 objectAtIndex:i], #"two":[_array1 objectAtIndex:i],#"three":[_array2 objectAtIndex:i]};
[finalArray addObject:dict];
}
NSLog(#"finalArray = %#", [finalArray description]);
You're reusing the keys ("one", "two" and "three") through each iteration of the loop. Keys in an NSDictionary have to be unique.
If you want many dictionary but only three keys, you should save each dict in an array.
Related
I got following response from server:
[{"bp":"000/000","dateTime":"05/12/2016 01:02:59 PM","doc":{"email_id":"batra#gmail.com","exception":0,"gender":"Male","id":0,"mobile_no":8055621745,"name":"Batra","profile_id":0,"qualification":"MD(Doctor)","reg_id":157,"salutation":"Mr","wellness_id":"251215782521"},"follow_up":"17","id":37,"medicine":["Syrup,Decold Total,20,0-0-1,Before Meal,1","Injection,Insulin,1,0-0-1,Before Meal,1","no","no","no","no","no","no","no","no"],"patient":{"email_id":"bishtrohit1989#gmail.com","exception":0,"gender":"Male","id":0,"mobile_no":8055621745,"name":"Rohit","profile_id":0,"qualification":"","reg_id":150,"salutation":"Mr","wellness_id":"290119935030"},"weight":"000"}]
From that I have separate the medicine array like following way:
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObject:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
NSLog(#"medicine: %#",Myarray);
I got output for this as like:
medicine: (
(
"Syrup,Decold Total,20,0-0-1,Before Meal,1",
"Injection,Insulin,1,0-0-1,Before Meal,1",
no,
no,
no,
no,
no,
no,
no,
no
)
)
Now what i want:
1) remove that all noelement.
2) after that, i want only 2nd element in each string.
in short i want my final output is like:
[Decold Total, Insulin];
But i don't know how to do that..??
Please anyone can solve my issue. help will be appreciable.
You need to use NSPredicate on Myarray and filter it.
Make your Myarray like this.
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObjectsFromArray:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
}
1) Remove that all no element.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (SELF = %#)",#"no"];
NSArray *filterArray = [Myarray filteredArrayUsingPredicate:predicate];
2) Want only 2nd element in each string
NSMutableArray *medicineArray = [[NSMutableArray alloc] init];
for (NSString* medicine in filterArray) {
NSArray *arr = [medicine componentsSeparatedByString:#","];
if (arr.count >= 2) {
[medicineArray addObject:[arr objectAtIndex:1]];
}
}
I ran into a problem and I can't find the method to get over it. basically I need to make a mutable dictionary with some values. All values are dynamic and I get them from web service or from other variables.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:comment.text forKey:#"Comment"];
[dict setObject:name.text forKey:#"Name"];
[dict setObject:[NSString stringWithFormat:#"%d",isPublic] forKey:#"VisibleForAll"];
po dict
{
Comment = "no comment";
Name = "test";
VisibleForAll = 1;
-> carts
}
Furthermore I want to add the following tree to my dictionary but I can't figure how to do this.
I have the necessary items in 2 NSArray artID and qty but I don't know how to create the bottom part so I can add it to the dict.
Carts {
Cart {
ArticleID : 22
Quantity : 1
}
Cart {
ArticleID : 45
Quantity : 3
}
...
}
I will add it with [dict setObject:carts forKey:#"Cart"] but I don't know how to add values in such a manner that I will make my dictionary on the form I presented you.
Also, don't forget that the numbers or Carts is flexible. I will get it from a Product.count.
Thanks in advance.
If your both array artID and qty have value at the same index for create a dictionary you can try like this
NSMutableArray *carts = [[NSMutableArray alloc] init];
for(NSInteger i=0; i<products.count; i++) {
//If you have custom class `cart` than use that
Cart *cart = [[Cart alloc] init];
cart.ArticleID = [[products objectAtIndex:i] valueForKey:#"pid"];
cart.Quantity = [[products objectAtIndex:i] valueForKey:#"qty"];
//If you not have any custom class than use Dictionary
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"ArticleID"];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"Quantity"];
}
Now add this carts array to Dictionary with key
[dict setObject:carts forKey:#"carts"];
NSArray *pid = [products valueForKey:#"pid" ];
NSArray *qty = [products valueForKey:#"qty"];
NSMutableArray *carts = [[NSMutableArray alloc] initWithCapacity:products.count];
for(NSInteger i=0; i<products.count; i++) {
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
NSMutableDictionary *cartemp = [[NSMutableDictionary alloc] init];
[cart setObject:[pid objectAtIndex:i] forKey:#"ArticleId"];
[cart setObject:[qty objectAtIndex:i] forKey:#"Quantity"];
[cartemp setObject:cart forKey:#"Cart"];
[carts addObject:cartemp];
}
[dict setObject:carts forKey: #"Carts"];
So! I have an NSDictionary that's pulling json out of my database just fine. I also have a mutable array that creates items for my beautiful SESpringboard view. The problem is that, initially, I only had a few items, so I was creating each item manually. But now that I have THOUSANDS of items I want to do something like a "while" loop in php that would just keep creating items until it goes through the whole table.
Here's the code I've got:
Goods *g = [[Goods alloc] init];
g.GID = [dict objectForKey:#"id"];
g.GName = [dict objectForKey:#"name"];
NSLog(#"bk:%#",g.GName);
g.GImg = [dict objectForKey:#"image"];
g.GDesc = [dict objectForKey:#"description"];
NSMutableArray *items = [NSMutableArray array];
[items addObject:[SEMenuItem initWithTitle:g.GName imageName:g.GImg viewController:self removable:NO]];
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
This works absolutely fine… except that what it does is place all the names and all the images one on top of another instead of creating a new item for each result.
If this were php I'd do something like "g.items" and it would just create a new item for each "g" but I'm not sure what to do here. Any help would be appreciated. (I googled but couldn't find anything like this for SESpringBoard items…)
Assuming you parse your json in a variable named allGoods, and that it's an array containing dictionaries representing your "Goods" objects.
You can do this:
NSMutableArray *items = [NSMutableArray array];
for (NSDictionary *dictionary in allGoods) {
[items addObject:[SEMenuItem initWithTitle:[dictionary objectForKey:#"name"] imageName:[dictionary objectForKey:#"image"] viewController:self removable:NO]];
}
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
I removed your usage of "Goods *g", as it looks like you don't need to keep a reference to such an object.
EDIT: here is the 5 items limit you requested
The "MIN" in the for loop is just in case allGoods contains less than 5 items.
for (int i = 0; i < MIN(5, allGoods.count); i++) {
NSDictionary *dictionary = [allGoods objectAtIndex:i];
[items addObject:[SEMenuItem initWithTitle:[dictionary objectForKey:#"name"] imageName:[dictionary objectForKey:#"image"] viewController:self removable:NO]];
}
SESpringBoard *thunderboard = [SESpringBoard initWithTitle:#"Boom" items:items launcherImage:[UIImage imageNamed:#"thor.png"]];
I am developing one iPad application.I have one NSMutableArray and NSMutableDictionary .These both are changeable based on the data from the web service.I need to remove some dictionary from my NSMutableArray based on the NSMutableDictionary values. Here I explain the situation through one example:
testArray =[{ language :"ESP"},{language :"ENG"},{language :"ENG"},{language :"FRH"}];
From the test array i need to remove the all Dictionaries which have key value language :"ENG".
I've written code like this:
for(int i =0;i<testArray.count;i++){
NSString *lang = [NSString stringWithFormat:#"%#", [testArray[i] objectForKey:#"language"]];
if([lang isEqualToString:#"ENG"]){
[testArray removeObjectAtIndex:i];
}
}
But it is not working. I think the problem is when I remove the dictionary from at index the array count is also reducing so the loop is executing based on new array count. Some help me to rewrite the code for get exact answer?
This is my favorite way, it's fast, clear and correct.
NSMutableArray *itemsToRemove = [NSMutableArray array];
for (id item in theArray) {
if ([item shouldBeRemoved])// Condition to check the key pair Value
[itemsToRemove addObject:item];
}
[theArray removeObjectsInArray:itemsToRemove];
Try this.
NSMutableArray *arrTemp = [[NSMutableArray alloc]initwithArray:testArray];
for(int i =0;i<testArray.count;i++){
NSString *lang = [NSString stringWithFormat:#"%#", [testArray[i] objectForKey:#"language"]];
if([lang isEqualToString:#"ENG"]){
[arrTemp removeObjectAtIndex:i];
}
}
[testArray removeAllObjects];
testArray = arrTemp;
for(int i =0;i<testArray.count;i++){
NSString *lang = [NSString stringWithFormat:#"%#", [testArray[i] objectForKey:#"language"]];
if([lang isEqualToString:#"ENG"]){
[testArray removeObjectAtIndex:i];
i--;
}
}
Replace your code with below code.
NSMutableArray *arrTemp = [NSMutableArray new];
for(int i =0;i<testArray.count;i++){
NSString *lang = [NSString stringWithFormat:#"%#", [testArray[i] objectForKey:#"language"]];
if([lang isEqualToString:#"ENG"]){
[arrTemp addObject:[NSNumber numberWithInt:i]];
}
}
for(int k=0;k<[arrTemp count];k++)
{
int ii = [[arrTemp objectAtIndex:k]intValue];
[testArray removeObjectAtIndex:ii];
}
let me know it is working or not!!!
Happy Coding!!!
I would implement that using NSPredicate:
NSMutableArray *testArray = [#[#{ #"language" :#"ESP"}, #{#"language" :#"ENG"},
#{#"language" :#"ENG"}, #{#"language" :#"FRH"}] mutableCopy];
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"language != %#", #"ENG" ];
testArray = [[testArray filteredArrayUsingPredicate:predicate] mutableCopy];
I have just tested it, it works (it is short and nice to read, but NSPredicate can be really slow).
Another way to do it is using enumerateObjectsWithOptions:usingBlock:
[testArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSDictionary *dict, NSUInteger index, BOOL *stop) {
if ([dict[#"language"] isEqualToString:#"ENG"]) {
[testArray removeObjectAtIndex:index];
}
}];
Pleace notice that i use NSEnumerationReverse as NSEnumerationOptions because according to docs of removeObjectAtIndex:- Method :
To fill the gap, all elements beyond index are moved by subtracting 1
from their index.
I want to get all key values in an array. Here I used the keyword allKeysForObject. While using allKeysForObject, I got value within parenthesis. I want to store value without parenthesis.
Here is my code:
dict = [[NSMutableDictionary alloc]init];
[dict setValue:#"Hai" forKey:#"1"];
[dict setValue:#"lrd" forKey:#"2"];
NSArray *keys = [dict allKeys];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
NSMutableArray *keyObjects = [[NSMutableArray alloc]init];
for(NSString* key in keys) {
NSString *obj = [dict objectForKey:key];
[countryArray addObject:obj];
}
for (int i =0; i < [countryArray count]; i++) {
[keyObjects addObject:[dict allKeysForObject: [countryArray objectAtIndex:i]]];
}
NSLog(#"%#",[keyObjects objectAtIndex:0]);
The NSLog value is:
2013-11-28 17:12:48.400 Help[6775:c07] (
1
)
Thanks in advance.
Replace:
NSLog(#"%#",[keyObjects objectAtIndex:0]);
With:
NSLog(#"%#",[keyObjects objectAtIndex:0][0]);
You are storing in keyObjects the value returned by allKeysForObject: which is a NSArray.
You will get all values in an NSDictionary using [dict allValues]. you dont need to manually iterate the array
dict = [[NSMutableDictionary alloc]init];
[dict setValue:#"Hai" forKey:#"1"];
[dict setValue:#"lrd" forKey:#"2"];
NSMutableArray *countryArray = [[dict allValues] mutableCopy];
NSMutableArray *keyObjects = [[NSMutableArray alloc]init];
for (int i =0; i < [countryArray count]; i++) {
[keyObjects addObject:[dict allKeysForObject: [countryArray objectAtIndex:i]]];
}
NSLog(#"%#",[keyObjects objectAtIndex:0][0]);
Instead of using loop for getting all key values from NSDictionary use - (NSArray *)allKeys;
method to do that. It is always good to use given methods than writing our own code to achieve the same.
so replace of the for loop with following code...
keyObjects = [[dict allKeys]mutableCopy]; // mutableCopy because I think you want it mutable as your array is mutable.
EDIT
AFA your code concern, your are getting parenthesis because you are storing all keys in keyObjects array as array, that why you can see those parenthesis out there in you log statement. and this is because allKeysForObject method returns array of keys related to given object.
and if you want it to be done in your way here it is...
for (int i =0; i < [countryArray count]; i++) {
[keyObjects addObject:[dict allKeysForObject: [[countryArray objectAtIndex:i]0]]];
}
While NSLog-ing:
Whenever you see (...) it is array.
Whenever you see {...} it is dictionary.
So in your case it is shown as (1) so this is an array with one object.
Hence you need to do through one level down to retrieve it.
NSLog(#"%#",[[keyObjects objectAtIndex:0] objectAtIndex:0]); //or
NSLog(#"%#",[keyObjects objectAtIndex:0][0]);