How to access a certain value in an NSArray? - iphone

I have an array called someArray. I would like to access the name value of the NSArray. I'm trying to access it using the following, but with out any luck. How do I do it properly?
cell.textLabel.text = [[someArray objectAtIndex:indexPath.row] objectForKey:#"name"];
some array {
haserror = 0;
headers = {
code = 0;
haserror = 0;
nodeid = "fe1.aaaaaa.2.undefined";
time = 16;
};
results = (
{
coords = (
"44.916667",
"8.616667"
);
id = 2;
key = alessandria;
name = Alessandria;
state = Piemonte;
zip = 1512;
},
{
coords = (
"43.616944",
"13.516667"
);
id = 3;
key = ancona;
name = Ancona;
state = Marche;
zip = 601;
},
}

As far as i see from you data model, the key name is a node under the key results. You can use this data model as a dictionary map, the code snippet below must give you what you need..
NSDictionary *myObject = [[someArray objectAtIndex:indexPath.row] objectForKey:#"results"];
cell.textLabel.text = [myObject objectForKey:"name"];
IMPORTANT NOTE: If you have some lopps or some other mechanisms for receiving data, there may be more efficent ways for your sıolution, so please give some more additional info about what you are exactly tryin to do

As others have noted, someArray is a dictionary while results is a key pointing to an array inside of your dictionary. If you want an array of all of the name fields in your results array, you could use valueForKeyPath: on the someArray variable, like this:
NSArray *names = [someArray valueForKeyPath:#"results.name"];
The names variable should now contain "Alessandria", and "Ancona" from the data set your show in your example code.

Related

How to identify the type of an object?

Here is my JSON response for a particular API.
Case 1
ChallengeConfiguration = {
AnswerAttemptsAllowed = 0;
ApplicantChallengeId = 872934636;
ApplicantId = 30320480;
CorrectAnswersNeeded = 0;
MultiChoiceQuestion = (
{
FullQuestionText = "From the following list, select one of your current or previous employers.";
QuestionId = 35666244;
SequenceNumber = 1;
},
{
FullQuestionText = "What color is/was your 2010 Pontiac Grand Prix?";
QuestionId = 35666246;
SequenceNumber = 2;
}
)
}
The key "MultiChoiceQuestion" returns an array with two questions. So here is my code.
let QuestionArray:NSArray = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as! NSArray
Case 2
ChallengeConfiguration =
{
AnswerAttemptsAllowed = 0;
ApplicantChallengeId = 872934636;
ApplicantId = 30320480;
CorrectAnswersNeeded = 0;
MultiChoiceQuestion = {
FullQuestionText = "From the following list, select one of your
current or previous employers.";
QuestionId = 35666244;
SequenceNumber = 1;
}
}
For Case 2 my code does not work and app crashes because it returns a dictionary for that specific Key. So how could I write a generic code that would work for all objects?
It looks like the key can contain either an array of dictionary values or a dictionary, so you just need to try casting to see which one you have.
so I would likely do it like this:
if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? Array {
// parse multiple items as an array
} else if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? [String:AnyObject] {
// parse single item from dictionary
}
You should never really use ! to force unwrap something unless you are completely certain that the value exists and is of the type you are expecting.
Use conditional logic here to test the response and parse it safely so that your app doesn't crash, even in failure.

Accessing info from NSDictionary based on print out

I'm using NSLog(#"%#", [filter attributes]); to print out the following from a dictionary:
CIAttributeFilterDisplayName = "Color Controls";
CIAttributeFilterName = CIColorControls;
inputBrightness = {
CIAttributeClass = NSNumber;
CIAttributeDefault = 0;
CIAttributeIdentity = 0;
CIAttributeSliderMax = 1;
CIAttributeSliderMin = "-1";
CIAttributeType = CIAttributeTypeScalar;
};
I'm a little confused about NSDictionarys and how the information is organized. If I needed to access the attributes for inputBrightness, what would be the syntax to retrieve this form the dictionary?
If you want to retrieve inputBrightness from dictionary filter, you can try this:
NSDictionary *inputBrightnessDict = filter[#"inputBrightness"]; //or [filter valueForKey:#"inputBrightness"];
This will return another dictionary with key value pairs CIAttributeClass:NSNumber, CIAttributeDefault:0 etc..
You can confirm that filter[#"inputBrightness"] is a dictionary by looking at the NSLog statement. Key value pairs enclosed in { and } represents a dictionary where as ( and ) represents an array.
Inorder to retrieve any value from inputBrightnessDict you can fetch it as, inputBrightnessDict[#"CIAttributeType"];
[filter objectForKey:inputBrightness];
Hope this helps..
Dictionary work with the concept of object and keys. You can retrieve an object using an key. Key-object come as a pair.

Weird value from NSDictionary

I got a NSDictionary that when I do a [currentOrder debugDescription] call on it the layout is below, when I then do a:
[currentOrder valueForKey: #"itemOrder"]
It return it funny with the brackets as:
(
"4 X ESPRESSO"
)
where it should only be (without brackets):
4 X EXPRESSO
Any idea why?
Content of currentOrder:
currentOrder: <__NSArrayM 0x68426c0>(
{
extra1Select = 0;
extra2Select = 0;
extra3Select = 0;
itemCost = 58;
itemOrder = "4 X ESPRESSO";
itemOrderDescription = "Cookie: YES, Sugar: YES";
itemQuantity = 4;
itemRestaurant = VidaECaffe;
plistItem = {
cost = "11.5";
description = "R11.50";
extra1 = {
desc = Cookie;
details = (
{
cost = "3.00";
option1 = YES;
},
{
cost = "0.00";
option2 = NO;
}
);
};
extra2 = {
desc = Sugar;
details = (
{
cost = "0.00";
option1 = YES;
},
{
cost = "0.00";
option2 = NO;
}
);
};
itemRestaurant = VidaECaffe;
level = 1;
title = ESPRESSO;
};
}
)
The problem is that currentOrder is not a dictionary but a NSArray containing a dictionary. The failure you are making next is that you use valueForKey: which is part of the key value coding family and not the designated access method for dictionaries (which is objectForKey:), and the array returns you a filtered array as a result...
When you print out the value of an array or dictionary in the debugger, the debugger includes the extra brackets, braces, and whatnot so you can see the layout of the structure you are asking about.
If the debugger shows the contents of an array something like
(
"Foobar"
)
it's telling you that the array has one element, a string with the value Foobar.
Put entirely another way: Read up on what the debugger does when it prints out values. Lots of resources here and on the web for this. For example: Debugging with GDB: Introduction to Commands, Print and Print-Object

How to get Facebook Photo Albums for iOS?

I'm making the following simple request to Facebook. My goal is to grab the names of all a user's photo albums:
[[AppDelegate sharedDelegate].facebook requestWithGraphPath:#"me/albums" andDelegate:[AppDelegate sharedDelegate]];
Then, I get a JSON response from the server like such:
data = (
{
"can_upload" = 1;
count = 4;
"cover_photo" = 321491374598618;
"created_time" = "2012-06-04T21:46:23+0000";
from = {
id = 100002132746588;
name = "Owner....";
};
id = 321491371265285;
link = "http://www.facebook.com/album.php?fbid=321491371265285&id=100002132746588&aid=73680";
name = "Photos";
privacy = custom;
type = normal;
"updated_time" = "2012-06-04T22:08:39+0000";
},
{
"can_upload" = 0;
count = 1;
"cover_photo" = 318401854907570;
"created_time" = "2012-05-31T00:00:35+0000";
description = "Which Friend Stalks You the Most?";
from = {
id = 100002132746588;
name = "Owner....";
};
id = 318401848240904;
link = "http://www.facebook.com/album.php?fbid=318401848240904&id=100002132746588&aid=73163";
name = "Which Friend Stalks You the Most?";
privacy = friends;
type = normal;
"updated_time" = "2012-05-31T00:00:36+0000";
},
And so on. Problem is, when I try to parse the data with:
NSLog(#"%#", [result objectForKey:#"name"]);
I get null. I assume this is happening because the NSDictionary that the data is returned in does not know which name entry to concentrate on. How do I parse the data so that I get the names of all the albums?
"result" is actually an array of dictionaries, so loop through the array and then grab name from each element in the array.
for (NSDictionary *anAlbum in [result objectForKey:#"data"]) {
NSLog(#"%#", [anAlbum objectForKey:#"name"]);
}

Obj-C / iPhone: NSArray question

I have an array that looks like this when printed via NSLog:
{
response = "Valid";
updates = (
{
string = "test";
integer = 3493;
},
{
string = "test2";
integer = 55454;
}
);
start-index = 0;
My question is how I can loop through through the "updates" array so that I may print the values for each "string" respectively.
Should be an easy "for" loop or something?
Dave
Assuming you NSLogged data has a type of NSDictionary with name data.
NSArray *updates = [data objectForKey:#"updates"];
for (NSDictionary *update in updates) {
NSLog(#"Update: %# - %#", [update objectForKey:#"string"], [update objectForKey:#"integer"]);
}