I need to create a NSMutableArray with dictionaries like the one shown below..Donno how to do it ./
(
{
businessName = "IBM Business Continuity & Recovery Service";
city = "Costa Mesa";
phone = "(714) 668-6900";
state = CA;
street = "600 Anton Blvd";
zip = 92626;
},
{
businessName = "IBM Sanno";
city = Lomita;
phone = "(310) 626-0613";
state = CA;
street = "25835 Appian Way";
zip = 90717;
},
{
businessName = "Ewert's IBM Typewriter Service";
city = "";
phone = "(559) 732-3215";
state = "";
street = "";
zip = "";
},
)
Please guide me
NSMutableDictionary *list = [[NSMutableDictionary alloc] init];
[list setObject:businessName.text forKey:#"businessName"];
[list setObject:city.text forKey:#"city"];
[list setObject:phone.text forKey:#"phone"];
[list setObject:state.text forKey:#"state"];
[list setObject:street.text forKey:#"street"];
[list setObject:zip.text forKey:#"zip"];
NSMutableArray *listArraySignup = [[NSMutableArray alloc] init];
[listArraySignup addObject:list];
If you want a NSMutableArray with dictionaries, you can do something like this
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity: 10];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity: 10];
[dict setObject: #"IBM Business Continuity & Recovery Service" forKey: #"businessName"];
set other objects like this
[array addObject: dict];
[dict release];
Add the other dictionaries like this in the array and you will be good to go :)
There are many ways to do this.
If you were planning on adding these dictionaries dynamically (roughly speaking):
NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
NSDictionary *exampleDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"IBM Business Continuity & Recovery Service", #"businessName",
#"Costa Mesa", #"city",
#"(714) 668-6900", #"phone",
#"CA", #"state",
#"600 Anton Blvd", #"street",
#"92626", #"zip", nil];
[dictionaries addObject:exampleDict];
with new Objective-C Literals
NSArray *array = #[
#{
#"businessName" : #"IBM Business Continuity & Recovery Service",
#"city" : #"Costa Mesa",
#"phone" : #"(714) 668-6900",
#"state" : #"CA",
#"street" : #"600 Anton Blvd",
#"zip" : #(92626)
},
#{
#"businessName" : #"IBM Sanno",
#"city" : #"Lomita",
#"phone" : #"(310) 626-0613",
#"state" : #"CA",
#"street" : #"25835 Appian Way",
#"zip" : #(90717)
},
#{
#"businessName" : #"Ewert's IBM Typewriter Service",
#"phone" : #"(559) 732-3215"
}
];
try this one, use NSDictionary
Related
Hi I have prepared static dictionary with data like Like
{ Age = 25, Name = Ajay;}
My requirement is I want to add this dictionary into My Array, I need a format like
({ Age = 25, Name = Ajay;})
My Code:
mainArray = [[NSMutableArray alloc] init];
dictMain = [[NSMutableDictionary alloc] init];
// dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
[dictMain setValue:#"Ajay" forKey:#"Name"];
[dictMain setValue:#"25" forKey:#"Age"];
[self dictMain];
I would do this like so:
NSArray *myArray = #[ #{#"Name": #"Ajay", #"Age": #"25"} ];
This will give you an immutable array with the data you want. Note though, that I would use #25 for your age (which will give you an NSNumber), instead of #"25", which will give you a string.
And if you really need to return a dictionary of an array of a dictionary, then you can do:
NSDictionary *myDict = #{ #[ #{#"Name": #"Ajay", #"Age": #"25"} ] };
Add NSDictionary to NSMutableArray.
NSMutableArray *mainArray = [[NSMutableArray alloc] init];
NSDictionary *dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
[mainArray addObject: dictMain];
Update:
NSDictionary *dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
NSArray *mainArry = #[dictMain];
NSDictionary *dict = #{#"key" : mainArry};
I have the following result of NSDictionary of Array
Bath = {
Keynsham = (
"nsham companies"
);
};
Bath = {
"Midsomer Norton" = (
"Keynsham companies"
);
};
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
};
Birmingham = {
"Acock's Green" = (
"Acock's Green taxi companies"
);
};
Birmingham = {
"Alcester Lane's End" = (
"Alcester Lane's End taxi companies"
);
};
How can i combine the values and keys so that I end up with only one category as shown below;
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
"Midsomer Norton" = (
"Keynsham companies"
);
Keynsham = (
"nsham companies"
);
};
I am not sure if this is the best way to explain it
the code is as follows
//all Nssarrays allocated/ initialised
NSURL *url=[NSURL URLWithString:#"http://y.php"];
NSData *data= [NSData dataWithContentsOfURL:url];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//instantiate arrays to hold data
NSMutableDictionary *dictArray=[[NSMutableDictionary alloc]init];
NSArray *cityName=[[NSArray alloc]init];
NSArray *townName=[[NSArray alloc]init];
NSArray *taxis=[[NSArray alloc]init];
NSArray *ids=[[NSArray alloc]init];
for (int i=0; i<json.count; i++)
{
//cityName=[[NSMutableArray alloc] initWithCapacity:json.count];
ids = [[json objectAtIndex:i] objectForKey:#"id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName=[[json objectAtIndex:i] objectForKey:#"townName"];
taxis=[[json objectAtIndex:i] objectForKey:#"taxis"];
NSMutableArray *taxisArray=[[NSMutableArray alloc] initWithObjects:taxis,nil];
NSMutableDictionary *towensdict=[[ NSMutableDictionary alloc] initWithObjectsAndKeys:taxisArray,townName, nil];
NSMutableDictionary *cities1=[[NSMutableDictionary alloc] initWithObjectsAndKeys:towensdict,cityName, nil];
NSLOG (#"%#", cities1) here, gives me the print out above
[dictArray addEntriesFromDictionary:cities1 ];
Then I tried Jdodgers solution as follows;
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
NSLog(#"%#", currentDictionary);
}
}
//this gives error "unrecognized selector sent to instance", here is the print out
combinedDictionary NSMutableDictionary * 0x000000010012e580
currentDictionary NSDictionary *const 0x0000000100116460
dictArray NSMutableDictionary * 0x000000010012e220
[0] key/value pair
key id 0x0000000100116460
[0] id
value id 0x000000010012e440
[0] id
keys NSArray * 0x0000000000000000
You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys.
For example, if your array was called dictArray, you could do:
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
}
}
This code first creates a dictionary combinedDictionary that will be your final dictionary. It loops through all of the dictionaries in your array and for each one does the following:
First, it gets an array of all keys in the dictionary. For the dictionaries you provided this array will look like #[#"Bath"] for the first 3 and #[#"Birmingam"] for the other two.
The code then loops through these keys and gets the already existing dictionary from the combined dictionary from this key. If the dictionary doesn't exist, one is created.
Then, it adds all of the values from the dictionary from the array and sets the new dictionary to be the one in combinedDictionary.
I have an array with multiple locations for different states.
{"location":"Lekki Phase 1","state":"abc","country":"Nigeria"},
{"location":"Lekki Phase 2","state":"xyz","country":"Nigeria"},
{"location":"Osapa London1","state":"def","country":"Nigeria"},
{"location":"Lekki Phase 2","state":"abc","country":"Nigeria"},
{"location":"Lekki Phase 3","state":"xyz","country":"Nigeria"},
{"location":"Osapa London 2","state":"def","country":"Nigeria"},..........
Now i can make an array for different states with no duplicate state , like
{"abc","xyz","def"}
But what i want is to display all locations state wise in a table.
How can i do this??
Using NSPredicate we can efficiently filter this . I have tried and tested working for me.
Here 'allDataArray' is array with dictionaries, You can replace your array here (the first one in your post)
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"Lekki Phase 1" forKey:#"location"];
[dict1 setObject:#"abc" forKey:#"state"];
[dict1 setObject:#"Nigeria" forKey:#"country"];
[allDataArray addObject:dict1];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"Lekki Phase 2" forKey:#"location"];
[dict1 setObject:#"xyz" forKey:#"state"];
[dict1 setObject:#"Nigeria" forKey:#"country"];
[allDataArray addObject:dict1];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"Lekki Phase 2" forKey:#"location"];
[dict1 setObject:#"abc" forKey:#"state"];
[dict1 setObject:#"Nigeria" forKey:#"country"];
[allDataArray addObject:dict1];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"Lekki Phase 3" forKey:#"location"];
[dict1 setObject:#"xyz" forKey:#"state"];
[dict1 setObject:#"Nigeria" forKey:#"country"];
[allDataArray addObject:dict1];
//NSLog(#"%#",allDataArray);
NSArray *state = [NSArray arrayWithObjects:#"abc",#"xyz", nil];
NSMutableArray *locationInState = [[NSMutableArray alloc] initWithCapacity:[state count]];
for(int i=0; i< [state count]; i++)
{
NSMutableArray *filteredarray = [[allDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(state == %#)", [state objectAtIndex:i]]] mutableCopy];
for(int j=0; j<[filteredarray count];j++)
{
NSDictionary *dict = [filteredarray objectAtIndex:j];
[filteredarray replaceObjectAtIndex:j withObject:[dict valueForKey:#"location"]];
}
[locationInState addObject:filteredarray];
}
NSLog(#"%#",locationInState);
Here locationInState array contains all location for filetred state. You can map them easily by index.
Result is
(
(
"Lekki Phase 1",
"Lekki Phase 2"
),
(
"Lekki Phase 2",
"Lekki Phase 3"
)
)
First It not array but it is Dictionary.
NSMutableDictionary * newDict = [NSMutableDictionary dictionaryWithCapacity:[OLdDict count]];
for(id item in [OLdDict allValues]){
NSArray * keys = [OLdDict allKeysForObject:item];
[newDict setObject:item forKey:[[OLdDict allKeysForObject:item] objectAtIndex:0]];
}
NSMutableDictionaries can act as uniquing collections (because they replace objects for keys if the same key is used twice). We can also take advantage of the fact that NSString is generally a constant address location, and funnel each one of those dictionaries into an array. To unique out each array of dictionaries, it would be far easier to wrap them in an object, but here goes:
-(void)uniquingSort {
//Setup collections for the uniquing process
NSMutableArray *datasource = //...
NSMutableIndexSet *hits = [NSMutableIndexSet indexSet];
NSMutableDictionary *uniquingDict = #{}.mutableCopy;
//Setup an index for the indexed set
int idx = 0;
//iterate through the array of dictionaries
for (NSArray *arrOfDicts in datasource) {
//get the dictionary we want to unique against
NSDictionary *innerDict = arrayOfDicts[1];
//do we have a dupe? If so, add its index to the index set
if (uniquingDict[innerDict[#"state"]] != nil)
[hits addIndex:idx];
uniquingDict[innerDict[#"state"]] = innerDict[#"state"];
idx++;
}
//cut out all the hits till we are only uniqued for the "state" key
[datasource removeObjectsAtIndexes:hits];
}
This code:
for (NSDictionary *object in JSONArray) {
NSMutableArray *birdtemp = [[NSMutableArray alloc] initWithObjects:object[#"case_name"], nil];
[allparts addObject:birdtemp];
}
outputs this log:
log: (
(
"NZXT Phantom 410"
),
(
"Thermaltake MK+"
)
)
I want to know what code I could use to make that log into one array like:
log: (
"NZXT Phantom 410",
"Thermaltake MK+"
)
Json Array is:
log: (
{
"case_color" = White;
"case_description" = "";
"case_image" = "http://sitecom/get/parts/part_images/nzxtphantom410.jpeg";
"case_name" = "NZXT Phantom 410";
"case_price" = "99.99";
"case_type" = ATX;
id = 1;
},
{
"case_color" = Black;
"case_description" = "";
"case_image" = "http://site.com/get/parts/part_images/thernaltake-mkplus.jpeg";
"case_name" = "Thermaltake MK+";
"case_price" = "84.99";
"case_type" = ATX;
id = 2;
}
)
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSDictionary *dict in JSONArray) {
[array addObject:[dict objectForKey:#"case_name"]];
}
NSLog(#"Your Array: %#",array);
I think it will be helpful to you.
A simple way to obtain the result you are looking for is to use key-value coding (KVC):
NSArray *allparts = [JSONArray valueForKey:#"case_name"];
Key-value coding used on arrays in this way may seem a bit counter-intuitive at first, but it is very powerful.
Troubleshooted and got this:
allparts = [[NSMutableArray alloc] init];
NSString *birdtemp;
for (NSDictionary *object in JSONArray) {
birdtemp = object[#"case_name"];
[allparts addObject:birdtemp];
}
NSMutableArray *birdtemp = [NSMutableArray ....];
for (NSDictionary *object in JSONArray) {
[birdtemp addObject:object[#"case_name"]];
}
[allparts addObject:birdtemp];
i want to remove object in Mutable array using mutable dictionary, How?
My code :
Employees *Emp7 = [[Employees alloc] init];
Emp7.Number = 7;
Emp7.Name = #"Safa'";
[EmployeesArray addObject:Emp1];
[Dictionary setValue:Emp1 forKey:Emp1.Name];
in the Deleting button (IBAction)
Employees *objEmp2 = [Dic1 objectForKey:objEmp1.Name ];
[Dic1 removeObjectForKey:#"Safa'"];
Please be a little more clear with your question, is this what you are looking for ?
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:values forKeys:keys];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
[array removeObject:[dict objectForKey:someKey]];
where 'values' and 'keys' are both arrays and 'somekey' is an object in the 'keys' array.
Please let me know if this helps.
TESTED CODE : 100 % WORKS
NSMutableArray *EmployeesArray = [[NSMutableArray alloc]init];
NSMutableArray *EmployeesArrayToDelete = [[NSMutableArray alloc]init];
Employees *Emp7 = [[Employees alloc] init];
Emp7.number = #"7"; Emp7.Name = #"Safa'";
[EmployeesArray addObject:Emp7];
Employees *Emp3 = [[Employees alloc] init];
Emp3.number = #"7"; Emp3.Name = #"AppleVijay#facebook.com";
[EmployeesArray addObject:Emp3];
Employees *EmployeToDelete = [[Employees alloc] init];
EmployeToDelete.number = #"7";
EmployeToDelete.Name = #"Safa'";
NSLog(#"before delete : %#",EmployeesArray);
for (Employees *eachEmployee in EmployeesArray) {
if ([eachEmployee.Name isEqual:EmployeToDelete.Name] && [eachEmployee.number isEqual: EmployeToDelete.number]) {
[EmployeesArrayToDelete addObject:eachEmployee];
}
}
if ([EmployeesArrayToDelete count]>0) {
[EmployeesArray removeObjectsInArray:EmployeesArrayToDelete];
}
NSLog(#" After delete Employeesarray : %#",EmployeesArray);