Accesing member items of NSDictionary inside an NSArray - iphone

I did a query to the Flickr API and It returned me with an NSArray containing dictionaries. I was wondering how i might be able to access lets the _content item of the array that was sent back to me.
NSArray *topPlaces = [FlickrFetcher topPlaces];
NSLog(#"%#",topPlaces);
(
{
"_content" = "London, England, United Kingdom";
latitude = "51.506";
longitude = "-0.127";
"photo_count" = 3061;
"place_id" = "hP_s5s9VVr5Qcg";
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+Kingdom/England/London";
timezone = "Europe/London";
woeid = 44418;
},
{
"_content" = "New York, NY, United States";
latitude = "40.714";
longitude = "-74.007";
"photo_count" = 1886;
"place_id" = ".skCPTpTVr.Q3WKW";
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+States/New+York/New+York";
timezone = "America/New_York";
woeid = 2459115;
},
{
"_content" = "Weston-Super-Mare, England, United Kingdom";
latitude = "51.346";
longitude = "-2.977";
"photo_count" = 945;
"place_id" = HWdHmQdVUrptMA;
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+Kingdom/England/Weston-Super-Mare";
timezone = "Europe/London";
woeid = 40016;
},
)

Just iterate over the NSArray like so
for (NSDictionary *dictionary in topPlaces) {
NSLog(#"%#", [dictionary objectForKey:#"_content"]);
}

Related

Sorting array of multiple dictionaries

My array contains three dictionaries per object of the array.
{
avg = {
avg1 = 50;
avg2 = 60;
};
posts = {
alcoholContent = 450;
name = "BBB";
origin = United States;
};
reviews = {
rev1 = "Test review 1";
rev2 = "Test review 2";
};
}
{
avg = {
avg1 = 30;
avg2 = 20;
};
posts = {
alcoholContent = 550;
name = "AAA";
origin = United States;
};
reviews = {
rev1 = "Test review 1";
rev2 = "Test review 2";
};
}
I want to sort array acceding by key "name" (of post dictionary).
How can I do it?
I tried normal sorting methods using sort descriptors, but did not work
Try sortUsingComparator:
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1 = [[dict1 objectForKey:#"posts"] objectForKey:#"name"];
NSString *string2 = [[dict2 objectForKey:#"posts"] objectForKey:#"name"];
return [string1 compare:string2];
}];

How Do I Sort By An Inner Array Using IOS

I have an NSArray and within the array each item has an inner array called "venue" and then within that another array called "location". I would like to sort the array by the "distance" value within each "location" array.
Can someone point me in the right direction, this is the array.
{
venue = {
beenHere = {
count = 0;
marked = 0;
};
location = {
address = "845 Market St.";
city = "San Francisco";
country = "United States";
crossStreet = "Westfield Food Emporium";
distance = 137;
lat = "37.78459765160777";
lng = "-122.40650538423186";
postalCode = 94103;
state = CA;
};
};
},{
venue = {
beenHere = {
count = 0;
marked = 0;
};
location = {
address = "845 Market St.";
city = "San Francisco";
country = "United States";
crossStreet = "Westfield Food Emporium";
distance = 137;
lat = "37.78459765160777";
lng = "-122.40650538423186";
postalCode = 94103;
state = CA;
};
};
},
At the minute I am using the following but it doesn't seem to be having any effect.
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey:#"distance" ascending: YES];
self.venueObject = [venueObject sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
Thanks
Oliver
If I understand your question correctly, you have an array of dictionaries, and want to sort buy some value within those dictionaries sub-keys.
You need to use the sortedArrayUsingComparator: method.
Something like this should work for you:
NSArray * sortedVenues = [venues sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * venue1, NSDictionary * venue2) {
float distance1 = [[venue1 valueForKeyPath: #"location.distance"] floatValue];
float distance2 = [[venue2 valueForKeyPath: #"location.distance"] floatValue];
if (distance1 > distance2) {
return NSOrderedDescending;
} else if (distance1 < distance2) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];

How to get values from unknown key in NSDictionary iphone?

I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);

Retrieve value from NSDictionnary

I have a NSDictionary and I don't know how I can retrieve the value of "#mode" and "#route" (this is from a json response).
How I can do that?
Thanks!
This is the NSDictionary :
{
"#mode" = WALK;
"#route" = "Rue University";
distance = "17.513516908661757";
duration = 13000;
endTime = "2011-04-29T12:08:59.395-04:00";
from = {
geometry = "{\"type\": \"Point\", \"coordinates\": [-73.57120386807037,45.503820214186405]}";
lat = "45.503820214186405";
lon = "-73.57120386807037";
name = "Rue University";
};
legGeometry = {
length = 3;
points = "{mvtG`k``MOd#ME";
};
startTime = "2011-04-29T12:08:46.395-04:00";
steps = {
walkSteps = (
{
absoluteDirection = NORTHWEST;
becomes = false;
distance = "17.513516908661757";
elevation = "";
lat = "45.503820214186405";
lon = "-73.57120386807037";
stayOn = false;
streetName = "Rue University";
},
{
absoluteDirection = NORTH;
becomes = true;
distance = "0.0";
elevation = "";
lat = "45.50390573910769";
lon = "-73.57139257694809";
relativeDirection = RIGHT;
stayOn = false;
streetName = "street transit link";
}
);
};
to = {
geometry = "{\"type\": \"Point\", \"coordinates\": [-73.571363,45.503971]}";
lat = "45.503971";
lon = "-73.571363";
name = "Station McGill";
stopId = 32;
};
Looks like object at index 0 is a NSDictionary.
NSDictionary *dict = [array objectAtIndex:0];
NSString *route = [dict objectForKey:#"#route"];
Try this:
[myDictionary objectForKey:#"#mode"];
Given an NSDictionary dict, you can retrieve the value corresponding to the key #mode using:
[dict objectForKey:#"#mode"];
Two possibilities:
1) The NSMutableArray is an array of JSON formatted strings.
2) The NSMutableArray is an array of NSDictionaries.
If its #1, then you need to use the Cocoa JSON stuff to decode the JSON string into an NSDictionary:
NSDictionary* aDict = [[myArray objectAtIndex:0] JSONValue];
OR
NSDictionary* aDict = [theArray objectAtIndex:0];
The JSON stuff is available here http://code.google.com/p/json-framework/
Then this should work:
NSString* theMode = [aDict objectForKey:#"#mode"];
NSLog(#"the mode is %#, as read from the dictionary %#", theMode, aDict);
--Tom

How to design Object Graph/Model?

JSON As Dictionary
{
headers = (
{
backGroundImageUrl = "";
dataField = Name;
headerText = Name;
id = Name;
itemRenderer = "";
toolTip = "";
width = 60;
},
{
backGroundImageUrl = "";
dataField = BidPrice;
headerText = Bid;
id = BidPrice;
itemRenderer = "";
toolTip = "Bid Price";
width = 30;
});
values = (
{
assetCellValueLst = {
AskColorCode = "#B8D1ED";
AskPrice = "102.20";
BidColorCode = "#B8D1ED";
BidPrice = "102.00";
Name = "AR Bonar 11";
PECSAsk = 569;
PECSChg = "(31)";
PECSChgColorCode = "#000000";
PriceChg = "0.00";
PriceChgColorCode = "#000000";
SOLAsk = 604;
SSPAsk = 677;
SSPChgDay = "+3";
SSPChgDayColorCode = "#000000";
YTMAsk = "6.97";
assetGroupName = Argentina;
assetId = ARBONAR11;
iconPath = "images/flag_Argentina.gif";
updated = false;
};
assetId = ARBONAR11;
},
{
assetCellValueLst = {
AskColorCode = "#53840f";
AskPrice = "84.00";
BidColorCode = "#53840f";
BidPrice = "83.75";
Name = "AR Bod 15";
PECSAsk = 945;
PECSChg = 14;
PECSChgColorCode = "#000000";
PriceChg = "-0.10";
PriceChgColorCode = "#53840F";
SOLAsk = 985;
SSPAsk = 1007;
SSPChgDay = "+7";
SSPChgDayColorCode = "#000000";
YTMAsk = "11.74";
assetGroupName = Argentina;
assetId = ARBON15;
iconPath = "images/flag_Argentina.gif";
updated = false;
};
assetId = ARBON15;
});
The above JSON has more headers and values shortened here for clarity. The assestCellValueLst Dictionary can have more or less key-value pair depending on business logic. Same is true for headers dictionary. How should I create a Object Model in Xcode to use it with Core Data Managed Objects ? for a non - persistent store or no store at all
Simplistically, you would just create an entity for each type of dictionary you wanted to persist and have an attribute for each key in the dictionary.
In this case it looks like you would have two entities: Header and Asset. If the headers have a one-to-relationship with assets you might have (pseudocode) entities like this:
Header{
backGroundImageUrl = string;
dataField = string;
headerText = string;
id = string;
itemRenderer = ?;
toolTip = ?
width = integer;
asset<--(required,cascade)-->Asset.header
}
Asset{
assetId = string;
askColorCode = string;
askPrice = float;
bidColorCode = string;
bidPrice = float;
//...etc
header<--(required,nullify)-->Header.asset
}
The basic idea is that the model, well, "models" whatever real world object, event, condition or information you want to persist. In this case, the JSON is providing nice, neat dictionaries with all the data already organized and labeled for you.
+(NSArray *)managedObjectsFromJSONDictionary:(NSDictionary *)dictionary withManagedObjectContext:(NSManagedObjectContext *)moc
{
NSMutableArray *finalArrayOfArrays = [[NSMutableArray alloc] init];
NSArray *allKeys = [dictionary allKeys];
for(NSString *keyName in allKeys)
{
id structureArray = [dictionary valueForKey:keyName];
if([structureArray isKindOfClass:[NSArray class]])
{
NSMutableArray *objectArray = [[NSMutableArray alloc] init];
for(NSDictionary *structureDictionary in (NSArray *)structureArray)
{
[objectArray addObject:[JSONtoManagedObject managedObjectFromDictionary:structureDictionary withManagedObjectContext:moc forEntity:keyName]];
}
[finalArrayOfArrays addObject:objectArray];
[objectArray release];
}
}
return [finalArrayOfArrays autorelease];
}
+(NSManagedObject *)managedObjectFromDictionary:(NSDictionary *)dictionary withManagedObjectContext:(NSManagedObjectContext *)moc forEntity:(NSString *)entityName
{
NSManagedObject *managedObject;
NSArray *arrayOfKeys = [dictionary allKeys];
for(NSString *name in arrayOfKeys)
{
id obj = [dictionary objectForKey:name];
managedObject = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:moc];
if (![obj isKindOfClass:[NSDictionary class]])
{
if([name isEqualToString:#"id"])
[managedObject setValue:obj forKey:#"uniqueID"];
else
[managedObject setValue:obj forKey:name];
}
else
{
NSDictionary *relationshipDictionary = [[managedObject entity] relationshipsByName];
for(NSString *relationshipName in [relationshipDictionary allKeys])
{
NSRelationshipDescription *relationshipDescription = [relationshipDictionary objectForKey:relationshipName];
if(![relationshipDescription isToMany] && [relationshipName isEqualToString:name])
{
NSManagedObject *childObject = [JSONtoManagedObject managedObjectFromDictionary:obj withManagedObjectContext:moc forEntity:relationshipName];
[managedObject setValue:childObject forKey:relationshipName];
continue;
}
NSMutableSet *relationshipSet = [managedObject mutableSetValueForKey:relationshipName];
NSArray *relationshipArray = [obj valueForKey:relationshipName];
for(NSDictionary *insideDictoinary in relationshipArray)
{
NSManagedObject *childObject = [JSONtoManagedObject managedObjectFromDictionary:insideDictoinary withManagedObjectContext:moc forEntity:relationshipName];
[relationshipSet addObject:childObject];
}
}
}//end else
} // for
return managedObject;
}