xcode iPhone array and dictionary [noob] - iphone

I'm sorry for this (probably very) noob question, but i've been asked about this and can't see what's wrong (i'm java tought..)
This is what I have, data is loaded via JSON:
NSDictionary *myvalues = [myres objectForKey:#"0"];
this is the content if I output via NSLog:
({id = "1a";myval = 5;},
{id = "2b";myval="24.6";})
how do I iterate through myvalues and how do I get the values id and myval? Something like this i'm getting stuck:
for (NSArray* myvals_array in myvalues)

First it looks like the returned value is an Array, the content inside of the parentheses() denotes this. So I would try and set it as such instead of a Dictionary. Then you can enumerate through the array of dictionary's and get each dictionary inside:
for (id object in myvalues) {
NSDictionary *currentObject = (NSDictionary*)object;
NSString *myID = [currentObject valueForKey:#"id"];
NSString *myValue = [currentObject valueForKey:#"myval"];
NSLog(#"ID:%# VALUE:%#",myID,myValue);
}
This will enumerate through the array and create a dictionary for each entry, then get the values for each of the two elements inside. I just NSLog() them here but you can do whatever you want with the values.

Related

Getting objectId from parse.com

So I am building an app that uses parse as a backend. I've written my own before but I figured I'll just save some time and use parse. I'm populating a table view with data from parse and that's fine. I want to grab the objectId from an dictionary built from an array from parse.
The output of my array is as follows:
<news_events:pdbIEvOteH:(null)> {\n eventDescription = \"This is a test description.\";\n eventMessage = \"This is a test message.\";\n eventTitle = \"Free Wi-Fi Now Available!\";\n}
The object ID is pdbIEvOteH in the example above. I at first tried getting the id by using:
NSString * objectId = [myDictionary objectForKey:#"objectId"]; But that returned null. I know it is not a problem with my dictionary because I can get other information. The problem is it looks like there is no key for objectId in the array above. As you can see it follows news_events.
I know you can get it with the PFObject but I'm not sure if I can populate a table with a PFObject.
So bottom line is how do I get the objectId.
In my didSelectRowAtIndexPath: method, I did the following:
PFObject *myObject = [parseArray objectAtIndex:indexPath.row];
NSString *objectId = [myObject objectId];
To get the Id of a particular PFObject.
In Swift:
var objectId = object.objectId
In Objective-C:
NSString *objectId = object.objectId;
"So bottom line is how do I get the objectId."
following is answer from 'Joe Blow' with actual/example code for ios.
i had similar issue. retrieving data with following code worked:
NSString *reporterOpinion = [NSString stringWithFormat:#"%#", [object objectForKey:#"reporterOpinion"]];
but trying to do objectForKey with objectId returned null:
NSString *objectId = [NSString stringWithFormat:#"%#", [object objectForKey:#"objectId]];
following 'Joe Blow' answer, the following code returned correct value for objectId:
NSString *objectId = object.objectId;

Update original NSMutableArray after filtering with NSPredicate

I have recently started programming for the iOS Platform but now I need some help figuring out how to do 'something':
For my application I fetch some JSON data and put this data as objects into an Array
This Array is written to my own PLIST file (in the docs directory)
Now when the users starts a sync action I:
Fetch the data from the PLIST
Get the timestamp for a certain object in the Array that came from the PLIST
Use timestamp in new JSON request (for the new data)
So far so good.
Now for my (current) problem -> After receiving the new data (JSON req) I wish to update the timestamp of this 'certain' object in the array (and write this to the Plist).
Using an NSPredicate I am able to find the right set of data within the main Array (stampArr).
NSString *documentsDir = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
NSString *plistPath = [documentsDir stringByAppendingPathComponent:#"stamps.plist"];
NSMutableArray *stampArr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"eventid = 1"];
NSMutableArray *filteredStampArr = [stampArr filteredArrayUsingPredicate:filter];
But now, after I update the filteredStampArr, I want to update the main Array with the data from the filtered Array.
In other words, I need to update the object from the Array with the new 'timestamp' (field of object).
I could off course use something like [stampArr addObject: [filteredStampArr copy]] after changing the filterd array but that would just create a duplicate of the information. I wish to overwrite the original object.
Somehow (I think) I need a 'pointer' that tells me the location of the data in the original array so that I can change the data directly in the main array?
(I hope my questions is clear - If not please say so)
Get the item, find it's index in stampArr and replace it with the newItem.
NSArray *filteredStampArr = [stampArr filteredArrayUsingPredicate:filter];
id item = [filteredStampArr objectAtIndex:0]; // id because the type of the item is not known
NSUInteger itemIndex = [stampArr indexOfObject:item];
[stampArr replaceObjectAtIndex:itemIndex withObject:newItem];
When you get filteredArray, you can directly update objects in it (not replace) and thay willbe uopdated in main array.
Read the API carefully!
try:
[stampArr filterUsingPredicate:];

parsing JSON object and sub-elements on iphone app

I am building an app that uses a UPC data base API. I am getting back a JSON object, example from here: http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php
{
"success":true,
"usedExternal":false,
"result"
{
"calories_per_serving":"150",
"cholesterol_per_serving":"15",
"cholesterol_uom":"Mg",
"dvp_calcium":"30",
"dvp_cholesterol":"4",
"dvp_iron":"2",
"dvp_protein":"17",
"dvp_saturated_fat":"8",
"dvp_sodium":"10",
"dvp_total_fat":"4",
"dvp_vitamin_a":"10","
"dvp_vitamin_c":"0",
"dvp_vitamin_d":"25",
"fat_calories_per_serving":"25",
"fiber_per_serving":"<1",
"fiber_uom":"G",
"ingredients":"Fat Free Milk, Milk, Sugar, Cocoa (Processed With Alkali),
Salt, Carrageenan, Vanillin (Artificial Flavor),
Lactase Enzyme, Vitamin A Palmitate And Vitamin D3.",
"protein_per_serving":"8",
"protein_uom":"G",
"size":"240",
"units":"mL",
"servings_per_container":"8",
"sodium_per_serving":"230",
"sodium_uom":"Mg",
"total_fat_per_serving":"2.5",
"total_fat_uom":"G",
"trans_fat_per_serving":"0",
"trans_fat_uom":"G",
"upc":"041383096013"
}
}
My problem is with parsing the "ingredients" element, which is a sub list of the object dictionary.
How would you suggest parsing the ingredients list? If I could get it to an NSArray, assuming commas are separators, that would have been great.
I tried to do this, but looks like its just a string, so no way to parse it.
Any suggestion would be more than welcome. Thanks!
//Thats the whole JSON object
NSDictionary *json_dict = [theResponseString JSONValue];
//Getting "results" which has all the product info
NSArray *myArray = [[NSArray alloc] init];
myArray = [json_dict valueForKey:#"result"];
Now how do I get "ingredients" from myArray in an array form?
You're getting result as an array, but (in JSON terminology) it's not an array. It's an object, so use an NSDictionary. Something like this:1
NSDictionary *result = [json_dict objectForKey:#"result"];
Then you can get the inner ingredients object from that:
NSString *ingredients = [result objectForKey:#"ingredients"];
Edited as per #Bavarious' comment.
1Apologies for glaring errors, as I'm not terribly well-versed in Objective-C. You might need to allocate memory for the returned NSDictionary and NSString pointers; I'm not sure.
Here's all you need to do:
NSDictionary *json_dict = [theResponseString JSONValue];
// Use a key path to access the nested element.
NSArray *myArray = [json_dict valueForKeyPath:#"result.ingredients"];
EDIT
Whoops, Matt's right. Here's how to deal with the string value:
// Use a key path to access the nested element.
NSString *s = [json_dict valueForKeyPath:#"result.ingredients"];
NSArray *ingredients = [s componentsSeparatedByString:#", "];
Note that you might need to trim the '.' character off the last element of the array.

How to refer to an object in a NSDictionary that is in a NSArray

When I NSLog the array I get this:
(
{
content = "content a";
id = 452069;
timestamp = 1313341470;
},
{
content = "content b";
id = 451498;
timestamp = 1313261505;
},
etc...
)
How do you refer to specific index's? For example how would you get the content for the second index.
I've tried [[myArray objectAtIndex:1]objectForKey:#"content"] but that crashes the program.
Also doing [myArray objectAtIndex:1] crashes the program as well.
According to your edit your array is likely over released. Make sure your array is properly retained, if it uses a property make sure the property is set to copy or retain and if you set it internally be sure to use self.myArray = ...; and not myArray = ...'.
Have you tried -valueForKey:? The item at that index is not an object but a value.

How to extract a string from a dictionary in an array into a different array

hello I have a NSMutableArray iconlocarr. I also have another array containing dictionary data called xmlnodes which looks like this:
{
nodeChildArray = (
{
nodeContent = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png";
}
);
nodeName = weatherIconUrl;
}
I am trying to add the nodeContent data (icon url) into my iconlocarr array:
[iconlocarr addObject:[[[xmlnodes objectAtIndex:i] objectForKey:#"nodeChildArray"] valueForKey:#"nodeContent"]];
The problem I have is that the above code adds the following data:
(
{
nodeContent = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png";
}
)
As well the data I actually want
"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
How do I just add the nodeContents data and not the rest? The intention is to pass the data to a NSURL
Are you sure that's what it's adding? From your code, I would expect it to add an array containing the nodeContent string, e.g.
(
#"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png;
)
The problem here is you're trying to extract a single value from an array (your nodeChildArray value) and you haven't defined exactly how you want to do that. Do you want the first item in the array? The last? A random item? You should figure that out. In any case, you can use
NSArray *ary = [[xmlnodes objectAtIndex:i] objectForKey:#"nodeChildArray"];
to get the nodeChildArray value and then determine how exactly you want to pick which value inside it to extract the contents from.
Try this instead:
iconlocarr addObject:[[[[xmlnodes objectAtIndex:i] objectForKey:#"nodeChildArray"] objectAtIndex:0] objectForKey:#"nodeContent"]];
which consider object "nodeChildArray" as an array, then extract index 0 and then the returned dictionary will contain the "nodeContent".
KVC should handle this easily:
for (id nodeContents in [xmlnodes valueForKeyPath:#"nodeChildArray.nodeContent"])
[iconlocarr addObjectsFromArray:nodeContents];