Fetch NSarray from the NSDictionary of NSArray using objectForKey - iphone

I have a NSArray which contain n number of NSDictionary sampleArray =
(
{
0 = 0;
1 = 0;
},
{
0 = 86400;
1 = 2;
},
{
0 = 172800;
1 = 4;
},
{
0 = 259200;
1 = 5;
}
)
Now I need to fetch the NSArray for objectForKey 0 [sampleArray objectForKey:[NSNumber numberWithInt:0]], my result NSArray should be like
(0,86400,172800,259200) but I am unable to fetch the result and the app crashes.
Normally for NSDictionary, if key value is set using NSString valueForKey the above operation is performed successfully but if key value is set using an object like NSNumber objectForKey I am unable to perform the operation.
Please help me to get a solution, any suggestion would be appreciated!!

A very straight forward way if your keys are NSNumber objects:
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSDictionary *d in a) {
if (d[#0]) {
[result addObject:d[#0]];
}
}

THIS doesnt work - im sorry: I didnt see you didnt have Strings as keys + I didnt know KVC only works with strings
I leave it though
what you are looking for is
NSArray *zeros = [mainArray valueForKey:#"0"];
it gets "0" from each dict in array

What you have do is
NSMutableArray *arrResult = [[NSMutableArray alloc]init];
for(int i=0;i<[sampleArray count];i++)
{
NSString *strValue = [[sampleArray objectAtIndex:i] valueforkey:#"0"];
[ arrResult addobject:strValue];
}
let me know it is working or not!!!!
Happy coding!!!!!

here you can try NSArray *tempArray
for (NSDictionary *list in tempArray)
{
[firstArray addObject:[list objectForKey:#"0"];
[secondArray addObject:[list objectForKey:#"1"];
}

Related

Convert Dictionaries into one array

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];

Getting Array with values from an array of NSDictionary

I have an array with 4 Dictionaries with key #"preference" like as follows
(
{
preference = Nose;
},
{
preference = "Heart rate";
},
{
preference = Glucose;
},
{
preference = Food;
}
)
Now i want to retrieve an array for these dictionary values like"
(
Nose, Heart rate, Glucose, Food
)
How s'd i get it.. Thanks in advance
A one-liner:
NSArray *resultingArray = [arrayOfDictionaries valueForKeyPath:#"preference"];
Try it:
NSArray *result = [dictionaryObject valueForKeyPath:#"preference"];
It'll solve your Problem
Do something like this:
NSMutableArray *collectedValues = [NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary *dict in array) {
NSString *value = [dict objectForKey:#"preference"];
if (value) {
[collectedValues addObject:value];
}
}
Try with this code:
myArray is your first array
mySecondArray is the array you have in the end
NSMutableArray *mySecondArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [myArray count] ; i++)
{
NSDictionary *tempDict = [myArray objectForIndex:i];
[mySecondArray addObject:[tempDict objectForKey#"preference"]];
}

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

can't acces key from NSDictionary

I have the following code:
- (id)initWithDictionaryRepresentation:(NSDictionary *)dictionary {
self = [super init];
if (self != nil) {
dictionaryRepresentation = [dictionary retain];
NSArray *allKeys = [dictionaryRepresentation allKeys];
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:#"Steps"];
numerOfSteps = [stepDics count];
steps = [[NSMutableArray alloc] initWithCapacity:numerOfSteps];
for (NSDictionary *stepDic in stepDics) {
[(NSMutableArray *)steps addObject:[UICGStep stepWithDictionaryRepresentation:stepDic]];
}
............
}
My app crashes at this line:
NSArray *stepDics = [k objectForKey:#"Steps"];
but also crashes if I try this : NSArray *stepDics = [k objectForKey:#"pr"];.It seems that I can't acces any of the keys!
This is how my dictionary looks like:
http://pastebin.com/w5HSLvvT
Any idea?
NSArray *allKeys = [dictionaryRepresentation allKeys];
Will return you the keys in an unpredictable order, so you shouldn't be using
id key = [allKeys objectAtIndex:[allKeys count] - 1]
as it could return something different every time, this is shown in the documentation for for this function in the NSDictionary Documentation.
The order of the elements in the array is not defined
Why dont you try
NSDictionary* a = [dictionary objectForKey:#"A"];
NSArray* stepDics = [a objectForKey:#"Steps"];
A dictionary will return nil if you ask for a key that doesn't exist. The fact that it's crashing means that you have a memory management error, not in the code you show above but in the code that creates the dictionary that is passed into your initWithDictionaryRepresentation: method. You're over-releasing the array that's stored in the #"Steps" key of the dictionary.

Finding the maximum elements in an NSArray (or NSMutableArray)

I am having a bit of trouble navigating around an NSArray.
My array:
Element[0] = "ElementA"
Element[1] = "ElementA"
Element[2] = "ElementA"
Element[3] = "ElementA"
Element[4] = "ElementB"
Element[5] = "ElementC"
Are there any methods in Objective-C that will help me find the "median" element? In this case, the "median" would be "ElementA", or the value that occurs the maximum number of times.
In C# this would be a single call, but I can't find an equivalent in Objective-C.
Many thanks,
Brett
Here's how I'd do it:
NSArray * elements = ...; //your array of elements:
NSCountedSet * counts = [NSCountedSet setWithArray:elements]:
id modeObject = nil;
NSUInteger modeCount = 0;
for (id element in counts) {
if ([counts countForObject:element] > modeCount) {
modeCount = [counts countForObject:element];
modeObject = element;
}
}
NSLog(#"element with highest frequency: %#", modeObject);
An NSCountedSet is an NSMutableSet that also remembers how many times its elements have been added to the array.
Wrote this just for you :)
- (NSString *) findModeString: (NSArray *) array {
NSMutableDictionary *stats = [[NSMutableDictionary alloc] init];
for(NSString *str in array) {
if(![stats objectForKey:str]) {
[stats setObject: [NSNumber numberWithInt:1] forKey:str];
} else {
[stats setObject: [NSNumber numberWithInt:[[stats objectForKey:str] intValue] + 1] forKey:str];
}
}
NSInteger maxOccurrences = 0;
NSString *max;
for(NSString *key in stats) {
if([[stats objectForKey:key] intValue] > maxOccurrences) {
max = key;
maxOccurrences = [[stats objectForKey:key] intValue];
}
}
[stats release];
return max;
}
EDIT: Although my solution works, you should upvote/accept #Dave DeLong's answer, it is much much better.
Couldn't you just use:
[myarray length] /2