I'm trying to create dictionary to POST JSON data to server:
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lon", nil];
NSArray *values = [NSArray arrayWithObjects: orderClass.extraLat, orderClass.extraLon, nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
this gives me:
{
lat = (
"54.720746",
"54.719206",
"54.717466"
);
lon = (
"56.011108",
"56.008510",
"56.007031"
);
}
But the aim is to POST data from arrays in format:
[{"lat":"54.720746", "lon":"56.011108" },
{ "lat":"54.719206", "lon":"56.008510"},
{ "lat":"54.717466", "lon":"56.007031"}]
Need your help.
Thanks for paying attention!
As I said in the comment - you need to reverse the steps towards your goal. First dictionaries, then array. And you'll get what you want.
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lon", nil];
NSArray *lats = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
NSArray *lons = [NSArray arrayWithObjects:#"4", #"5", #"6", nil];
// your way (not what you want)
NSArray *values = [NSArray arrayWithObjects: lats, lons, nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
// my recommendation based on what you want
NSMutableArray *postData = [[NSMutableArray alloc] init];
for (int i = 0; i < lats.count; i++) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[lats objectAtIndex:i] forKey:#"lat"];
[dict setObject:[lons objectAtIndex:i] forKey:#"lon"];
[postData addObject:dict];
}
This will get you these results:
(lldb) po postDict
{
lat = (
1,
2,
3
);
lon = (
4,
5,
6
);
}
And
(lldb) po postData
<__NSArrayM 0x7ffb5be4d950>(
{
lat = 1;
lon = 4;
},
{
lat = 2;
lon = 5;
},
{
lat = 3;
lon = 6;
}
)
Related
i have an array with 12 sections and i need to replace value at index.
My test code:
NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:#{#"first": #[#"test1", #"test2"]}, #{#"second": #[#"test1"]}, nil];
NSLog(#"%#", [hm valueForKey:#"first"][0][0] );
[[hm valueForKey:#"first"][0] replaceObjectAtIndex:0 withObject:#"lol"];
NSLog(#"%#", hm);
First NSLog returns : test1 - its ok
When replace - crash with -[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x7fde53d2f700
I need to change test1 to something.
Wha am i doing wrong please?
NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:#{#"first": #[#"test1", #"test2"]}, #{#"second": #[#"test1"]}, nil];
NSLog(#"%#", [hm valueForKey:#"first"][0][0] );
//Your inner array is immutable, change it to mutable and replace the object, That's it.
NSMutableArray *array = [[hm valueForKey:#"first"][0] mutableCopy];
[array replaceObjectAtIndex:0 withObject:#"lol"];
[hm replaceObjectAtIndex:0 withObject:array];
NSLog(#"%#", hm);
NSMutableArray *arr = [[NSMutableArray alloc] initwithArray[[hm objectAtIndex:0]objectForKey:#"first"]];
[arr replaceObjectAtIndex:0 withObject:#"lol"];
[hm replaceObjectAtIndex:0 withObject:arr];
You have to make mutable dictionary and array structure
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Joe",#"firstname",
#"Bloggs",#"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Simon",#"firstname",
#"Templar",#"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Amelia",#"firstname",
#"Pond",#"surname",
nil],
nil];
NSLog(#"Before - %#",names);
[names replaceObjectAtIndex:0 withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Joe_New",#"firstname",
#"Bloggs_New",#"surname",
nil]];
NSLog(#"After - %#",names);
Before - (
{
firstname = Joe;
surname = Bloggs;
},
{
firstname = Simon;
surname = Templar;
},
{
firstname = Amelia;
surname = Pond;
}
)
After - (
{
firstname = "Joe_New";
surname = "Bloggs_New";
},
{
firstname = Simon;
surname = Templar;
},
{
firstname = Amelia;
surname = Pond;
}
)
NSMutableArray *hm = [[NSMutableArray alloc] initWithObjects:#{#"first": #[#"test1", #"test2"]}, #{#"second": #[#"test1"]}, nil];
NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[hm objectAtIndex:0]];
NSMutableArray *array=[NSMutableArray arrayWithArray:[dic objectForKey:#"first"]];
[array replaceObjectAtIndex:0 withObject:#"lol"];
[dic setObject:array forKey:#"first"];
[hm replaceObjectAtIndex:0 withObject:array];
O/P (ViewController.m:48) (
(
lol,
test2
),
{
second = (
test1
);
}
)
I have no problems to get the value of name in terms (name of my blog post category) out of the xmlrpc server response object ...
Server response:
responseArray: (
{ guid = "http://www.domain.com/wp/?p=12";
"post_id" = "123";
terms = (
{ name = "Uncategorized"; }
);
}
)
... with the following lines of Objective-C code:
NSMutableArray *responseArray = [[NSMutableArray alloc] init];
responseArray = [nodeSaveResponse object];
for(i = 0; i < responseArray.count; i++) {
NSString *postLink = [[responseArray objectAtIndex: i] valueForKey: #"guid"];
NSString *postId = [[responseArray objectAtIndex: i] valueForKey: #"post_id"];
NSMutableArray *catArray = [[NSMutableArray alloc] init];
catArray = [[responseArray objectAtIndex: i] valueForKey: #"terms"]];
NSArray *cat = [catArray valueForKey: #"name"];
NSString *myCatString = [cat objectAtIndex: 0];
}
But to send a new blog post fails because the following code to pack the category string is somehow wrong:
NSString *myCatString = #"MyCategory";
NSMutableDictionary *name = [[NSMutableDictionary dictionaryWithObjectsAndKeys: myCatString, #"name", nil];
NSMutableArray *catArray = [[NSMutableArray arrayWithObject: name];
NSMutableDictionary *values = [[NSMutableDictionary alloc] init];
[values setObject: title forKey: #"post_title"];
// and so on with other values - until here everything works well
[values setObject: catArray forKey: #"terms"]; // if this line is called, the request fails
NSArray *params = [NSArray arrayWithObjects: #"1", user, pass, values, nil];
[myRequest setMethod: #"wp.newPost" withParameter: params];
Any idea, where my fault is?
Cheers, Martin
UPDATE
Whenever I comment out these lines writeToFile will create a file but if I dont,it will not work.
Here is my code..
NSMutableDictionary *allData = [[NSMutableDictionary alloc] init];
NSArray *countries = [self retrieveCountries];
for(NSDictionary *dicCountry in countries){
NSString *countryName = [dicCountry objectForKey:#"en_name"];
NSArray *capital = [self retrieveCapitals:countryName];
NSMutableDictionary *capitalInfo = [[NSMutableDictionary alloc] init];
for(NSDictionary *dictPerCap in capital){
NSString *cap = [dictPerCap objectForKey:#"en_name"];
NSArray *items = [self retrieveItems:cap];
NSArray *categories = [self retrieveCategories:cap];
if(items == nil)
items = [[NSArray alloc] init];
if(categories == nil)
categories = [[NSArray alloc] init];
// store data in a dictionary
NSDictionary* tempCapDic = [NSDictionary dictionaryWithObjectsAndKeys:
items, #"items",
categories, #"categories",
nil];
//store
[capitalInfo setObject:tempCapDic forKey:cap];
}
// store data in a dictionary
NSDictionary* dataDic = [NSDictionary dictionaryWithObjectsAndKeys:
capital, #"capitals",
capitalInfo, #"info",
nil];
//store
[allData setObject:dataDic forKey:countryName];
}
/**************************/
NSDictionary *rootDict = [NSDictionary dictionaryWithObjectsAndKeys:countries, #"detailedCountries", allData, #"all", nil];
The lines that needs to be commented out inorder to work are:
capital, #"capitals",
capitalInfo, #"info",
in NSDictionary* tempCapDic.
Any idea on how to fix this?
I have NSMutableArray data as below.
(
{
Id = 3;
Name = Fahim;
},
{
Id = 2;
Name = milad;
},
{
Id = 1;
Name = Test;
}
)
Now I want to update the name from Test to Omar (for id = 1).
Any idea how to get this done?
Answer
With below answer, I was getting error as -[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance. To resolve that issue I Changed [feeds addObject:[item copy]] to [feeds addObject:item]
for (NSMutableDictionary* aDict in yourMutableArray) {
if (aDict[#"id"] == 1) {
[aDict setObject:#"Omar" forKey:#"Name"];
}
}
EDIT :
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSDictionary* item1Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"id",
#"Fahim",#"name"
, nil];
NSMutableDictionary* item1 = [NSMutableDictionary dictionaryWithDictionary:item1Dict];
[mutableArray addObject:item1];
NSDictionary* item2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"2",#"id",
#"milad",#"name"
, nil];
NSMutableDictionary* item2 = [NSMutableDictionary dictionaryWithDictionary:item2Dict];
[mutableArray addObject:item2];
NSDictionary* item3Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"3",#"id",
#"test",#"name"
, nil];
NSMutableDictionary* item3 = [NSMutableDictionary dictionaryWithDictionary:item3Dict];
[mutableArray addObject:item3];
NSLog(#"%#",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[#"id"] isEqualToString:#"3"]) {
[aDict setObject:#"Omar" forKey:#"name"];
}
}
NSLog(#"%#",mutableArray);
And for much elegant:
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSArray* name = [NSArray arrayWithObjects:#"Fahin",#"milad",#"test", nil];
for (int i = 0; i < name.count; i++) {
NSDictionary* itemd = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"%i",i],#"id",
name[i],#"name"
, nil];
NSMutableDictionary* item = [NSMutableDictionary dictionaryWithDictionary:itemd];
//or
//NSMutableDictionary* item = [item mutableCopy];
[mutableArray addObject:item];
}
NSLog(#"%#",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[#"id"] isEqualToString:#"2"]) {
[aDict setObject:#"Omar" forKey:#"name"];
}
}
NSLog(#"%#",mutableArray);
logs are:
2013-10-18 00:51:48.845 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = test;
}
)
second log:
2013-10-18 00:52:06.887 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = Omar;
}
)
EDIT2 for copy:
-copy, as implemented by mutable Cocoa classes, always returns their immutable counterparts. When an NSMutableDictionary is sent -copy, it returns an NSDictionary containing the same objects. NSMutableDictionary is a subclass of NSDictionary, the compiler doesn't complain. NSDictionary does not recognize it's mutable subclass' methods (because it cannot mutate it's contents).
I have an array of strings that I want to use as the filter for another array of dictionaries that is created from a plist. For example, if I had a plist of dictionaries that looked like so:
Key: Value:
car1 audi
car2 bmw
car3 bmw
car4 audi
car5 jaguar
and my array of strings was "audi, jaguar". How would I code it so that I can create a new array that would return "car1, car4, car5"? Hope this makes sense. Or better yet, how can I walk down this dictionary and filter it based on a value and then create a new array of dictionaries to use.
Code:
-(void)plotStationAnnotations {
desiredDepartments = [[NSMutableArray alloc] init];
BOOL tvfrSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"tvfrSwitchStatus"];
BOOL hfdSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"hfdSwitchStatus"];
if (tvfrSwitchStatus) {
NSString *tvfr = #"TVF&R";
[desiredDepartments addObject:tvfr];
}
if (hfdSwitchStatus) {
NSString *hfd = #"HFD";
[desiredDepartments addObject:hfd];
}
NSLog(#"Array 1 = %#", desiredDepartments);
NSString *path = [[NSBundle mainBundle] pathForResource:#"stationAnnotations" ofType:#"plist"];
NSMutableArray *anns = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSMutableArray *newDictionaryArray = [NSMutableArray array];
for (NSDictionary *dictionary in anns) {
for (NSString *string in desiredDepartments) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}
NSLog(#"Array = %#", keyMutableArray);
for (int i = 0; i < [keyMutableArray count]; i++) {
float realLatitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"latitude"] floatValue];
float realLongitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"longitude"] floatValue];
StationAnnotations *myAnnotation = [[StationAnnotations alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [[keyMutableArray objectAtIndex:i] objectForKey:#"station"];
myAnnotation.subtitle = [[keyMutableArray objectAtIndex:i] objectForKey:#"department"];
[mapView addAnnotation:myAnnotation];
}
}
May be something like
NSArray *array1;
if([array1 containsObject : someValue])
can help. someValue can be your values you want to check if they exist in array1.
You can do something like this to filter by keys:
NSArray *keysToLookFor = [NSArray arrayWithObjects:#"car1", #"car4", #"car5", nil];
NSArray *foundObjects = [dictionary objectsForKeys:keysToLookFor notFoundMarker:nil];
Or something like this to filter by values:
NSString *valueToLookFor = #"Audi";
NSArray *keyArray = [dictionary allKeysForObject:valueToLookFor];
// To filter by multiple values
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
NSMutableArray *keyMutableArray = [NSMutableArray array];
for (NSString *string in valuesToFilterBy) {
[keyMutableArray addObjectsFromArray:[dictionary allKeysForObject:string]];
}
Updated answer for dictionaries in arrays:
NSArray *dictionaryArray; // The array of dictionaries that you have
NSMutableArray *newDictionaryArray = [NSMutableArray array];
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
for (NSDictionary *dictionary in dictionaryArray) {
for (NSString *string in valuesToFilterBy) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}