How to iterate through an NSArray containing NSDictionaries? - iphone

I have an NSArray of NSDictionaries each of which has 4 key values.
I'm creating objects for each NSDictionary and assigning the keys accordingly.
How can I iterate through the array of dictionaries and set each key as an attribute for the object?
I created the array seen in the picture below with this code:
if (muscleArray == nil)
{
NSString *path = [[NSBundle mainBundle]pathForResource:#"data" ofType:#"plist"];
NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path];
self.muscleArray = rootLevel;
}
NSMutableArray *arrayForSearching = [NSMutableArray array];
for (NSDictionary *muscleDict in self.muscleArray)
for (NSDictionary *excerciseDict in [muscleDict objectForKey:#"exercises"])
[arrayForSearching addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[excerciseDict objectForKey:#"exerciseName"], #"exerciseName",
[muscleDict objectForKey:#"muscleName"], #"muscleName",
[muscleDict objectForKey:#"musclePicture"], #"musclePicture", nil]];
self.exerciseArray = arrayForSearching;
NSString *path = [[NSBundle mainBundle] pathForResource:#"ExerciseDescriptions"
ofType:#"plist"];
NSDictionary *descriptions = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableArray *exercises = self.exerciseArray;
for (NSInteger i = 0; i < [exercises count]; i++) {
NSDictionary *dict = [[exercises objectAtIndex:i] mutableCopy];
NSString *exerciseName = [dict valueForKey:#"exerciseName"];
NSString *description = [descriptions valueForKey:exerciseName];
[dict setValue:description forKey:#"exerciseDescription"];
[exercises replaceObjectAtIndex:i withObject:dict];
}
The code to create one object would look like this:
PFObject *preloadedExercises = [[PFObject alloc] initWithClassName:#"preloadedExercises"];
[preloadedExercises setObject:exerciseName forKey:#"exerciseName"];
[preloadedExercises saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
NSLog(#"Success");
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
The array of dictionaries looks like this:

// Assuming you want to do something with all of these objects you're creating
// We'll start by creating an NSMutableArray
NSMutableArray *newObjects = [NSMutableArray arrayWithCapacity:arrayOfDictionaries.count];
for (NSDictionary *dictionary in arrayOfDictionaries)
{
PFObject *object = [PFObject objectWithClassName:#"preloadedExercises"];
object.exerciseDescription = [dictionary objectForKey:#"exerciseDescription"];
object.exerciseName = [dictionary objectForKey:#"exerciseName"];
object.muscleName = [dictionary objectForKey:#"muscleName"];
object.musclePicture = [dictionary objectForKey:#"musclePicture"];
// Add object to mutable array
[newObjects addObject:object];
}

After a quick glance at the Parse SDK that you mentioned in the comments, I think what you are looking for is this:
NSMutableArray *exercisesArray = [[NSMutableArray alloc] init];
PFObject *preloadedExercises;
id value;
// Iterate through your array of dictionaries
for (NSDictionary *muscleDict in self.muscleArray) {
// Create our object
preloadedExercises = [PFObject objectWithClassName:#"preloadedExercises"];
// For each dictionary, iterate through its keys
for (id key in muscleDict) {
// Grab the value
value = [muscleDict objectForKey:key];
// And assign each attribute of the object to the corresponding values
[preloadedExercises setObject:value forKey:key];
}
// Finally, add this newly created object to your array
[exercisesArray addObject: preloadedExercises];
}

for(NSDictionary* dictionary in yourArray){
// here you can iterate through. and assign every dictionary as you wish to.
}

Related

Split array into three separate arrays

I have an array and I want to split that array into 3 parts or 3 arrays.
1st array contains -> AppName
2nd array contains -> Description
3rd array contains -> Icon
Here is the json array I want to split,
Deviceinfo = (
{
Appname = App;
Description = "This is test app";
Icon = "57.png";
}
);
}
Here is my code for this,
NSMutableArray *firstArray = [NSMutableArray array];
NSMutableArray *secondArray = [NSMutableArray array];
NSMutableArray *thirdArray = [NSMutableArray array];
for (int i = 0; i < [json count]; i++) {
NSArray *tempArray = [[json objectAtIndex:i]componentsSeparatedByString:#""];
[firstArray addObject:[tempArray objectAtIndex:0]];
[secondArray addObject:[tempArray objectAtIndex:1]];
if ([tempArray count] == 3)
{
[thirdArray addObject:[tempArray objectAtIndex:2]];
}
}
NSLog(#"yourArray: %#\nfirst: %#\nsecond: %#\nthird: %#", json, firstArray, secondArray, thirdArray);
I observe a crash in the code at this line,
NSArray *tempArray = [[json objectAtIndex:i]componentsSeparatedByString:#""];
I don't understand what is going wrong here. Any pointers to solve this issue?
I think you can using below code i hope this help's you :-
NSMutableArray *firstArray = [NSMutableArray array];
NSMutableArray *secondArray = [NSMutableArray array];
NSMutableArray *thirdArray = [NSMutableArray array];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonResponse options: NSJSONReadingMutableContainers error: &e];
//here is first i load with Dicutionary bcz if into your Json you have may be multiple Dictuionary so you then you can load purticular dictionary as bellow line
EDIT
NSArray * responseArr = jsonArray[#"Deviceinfo"];
firstArray = [responseArr valueForKey:#"Appname"];
secondArray = [responseArr valueForKey:#"Description"];
thirdArray = [responseArr valueForKey:#"Icon"];
if you have multiple Deviceinfo dictionary in to your Json then you could use For loop
// NSArray * responseArr = jsonArray[#"Deviceinfo"];
// for (NSDictionary *dict in responseArr) {
// [firstArray addObject:[dict valueForKey:#"Appname"];
// [secondArray addObject:[dict valueForKey:#"Description"];
// [thirdArray addObject:[dict valueForKey:#"Icon"];
// }
NSMutableArray *firstArray = [[NSMutableArray alloc]init];
NSMutableArray *secondArray = [[NSMutableArray alloc]init];
NSMutableArray *thirdArray = [[NSMutableArray alloc]init];
NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
NSArray * tempArray = jsonArray[#"Deviceinfo"];
for (NSDictionary *list in tempArray)
{
[firstArray addObject:[list objectForKey:#"Appname"];
[secondArray addObject:[list objectForKey:#"Description"];
[thirdArray addObject:[list objectForKey:#"Icon"];
}
Then try
NSLog(#"yourArray: %#\nfirst: %#\nsecond: %#\nthird: %#", tempArray, firstArray, secondArray, thirdArray);
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://url.to.your.json"]];
NSArray *jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *appNameArray = [NSMutableArray array];
NSMutableArray *discriptionArray = [NSMutableArray array];
NSMutableArray *iconArray = [NSMutableArray array];
for(NSDictionary *dictionary in jsonObjects)
{
[appNameArray adddObject:[dictionary valueForKey:#"Appname"];
[appNameArray adddObject:[dictionary valueForKey:#"Description"];
[appNameArray adddObject:[dictionary valueForKey:#"Icon"];
}

Convert NSString to NSDictionary separated by specific character

I need to convert this "5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21" string into dictionary. Separated by "?"
Dictionary would be some thing like
{
sometext1 = "5",
sometext2 = "8",
sometext3 = "519223cef9cee4df999436c5e8f3e96a",
sometext4 = "EVAL_TIME",
sometext5 = "60",
sometext6 = "2013-03-21"
}
Thank you .
Break the string to smaller strings and loop for them.
This is the way
NSArray *objects = [inputString componentsSeparatedByString:#"?"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
int i = 1;
for (NSString *str in objects)
{
[dict setObject:str forKey:[NSString stringWithFormat:#"sometext%d", i++]];
}
Try
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
//This is very risky, your code is at the mercy of the input string
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (int idx = 0; idx<[stringComponents count]; idx++) {
NSString *value = stringComponents[idx];
NSString *key = keys[idx];
[dictionary setObject:value forKey:key];
}
EDIT: More optimized
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:stringComponents forKeys:keys];
first separate the string into several arrays by '?'.
then add the string in you dictionary.
sth like this:
NSString *str = #"5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *valueArray = [str componentsSeparatedByString:#"?"];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
for (int i = 0; i <[valueArray count]; i ++) {
[keyArray addObject:[NSString stringWithFormat:#"sometext%d",i+1]];
}
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
For the future: If you were to store your data in JSON format (closer to what you have anyway), it'll be much easier to deal with and transfer between systems. You can easily read it...using NSJSONSerialization

How to fetch data from pList in Label

I have a RegistrationController screen to store email-id ,password,DOB,Height,Weight and logininController screen to match email-id and password to log-in purpose.
Now, In some third screen I have to fetch only the Height,Weight from the plist of the logged-in user to display it on the label.now if I Store the values of email-id and password in from LoginViewController in string and call it in the new screen to match if matches then gives Height,Weight ..if it corrects then how to fetch Height,Weight from the plist of the same one.
How can I fetch from the stored plist in a string?
Here is my code:
-(NSArray*)readFromPlist
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *valueArray = [dict objectForKey:#"title"];
return valueArray;
}
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}
First get whole value from your plist file after that store this NSArray into NSMutableArray and get the value with its objectAtIndex and valueForKey property..see whole example bellow..
UPDATE :
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"yourFileName" ofType:#"plist"];
NSArray *contentArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithArray:contentArray];
for (int i = 0; i< [yourArray count]; i++)
{
id object = [yourArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
yourLableWeight.text = [[objDict objectForKey:#"Weight"];// set index with your requirement
yourLableHeight.text = [[objDict objectForKey:#"Height"];
}
hope this help you...
When you enter credentials on login screen to check when it match the credentials with the fetched plist then pass that plist to the next controller. Do something like this
UserViewController *controller = [[UserViewController alloc] initWithNibName:#"UserViewController" bundel:nil];
[controller setUserDictionary:yourPlistDictionary];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
in UserViewController you would have a NSDictionary instance to store the data to show, hope that will help you

returning 8 closest cgfloat from a table lookup based on a cgfloat

I am trying to create this method. Let's call this
-(NSMutableArray*) getEightClosestSwatchesFor:(CGFloat)hue
{
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
NSLog(#"[plistData valueForKey:aKey] string] is %f", [[dict valueForKey:#"hue"] floatValue]) ;
}
return myArray;
}
pretty much, I am passing a cgfloat to this method which then needs to check a plist file which have hue key for 100 elements. I need to compare my hue with all of the hues and get 8 most closest hue and finally wrap these into an array and return this.
What would be most efficient way of doing this? Thanks in advance.
Here's my method if anyone is interested. Feel free to comment on it.
-(NSArray*)eightClosestSwatchesForHue:(CGFloat)hue
{
NSMutableArray *updatedArray = [[NSMutableArray alloc] initWithCapacity:100];
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
CGFloat differenceHue = fabs(hue - [[dict valueForKey:#"hue"] floatValue]);
//create a KVA for the differenceHue here and then add it to the dictionary and add this dictionary to the array.
NSDictionary* tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
[dict valueForKey:#"id"], #"id",
[NSNumber numberWithFloat:differenceHue], #"differenceHue",
[dict valueForKey:#"color"], #"color",
nil];
[updatedArray addObject:tempDict];
}
//now we have an array of dictioneries with values we want. we need to sort this from little to big now.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"differenceHue" ascending:YES];
[updatedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
//now get the first 8 elements and get rid of the remaining.
NSArray *finalArray = [updatedArray subarrayWithRange:NSMakeRange(0,8)];
[updatedArray release];
return finalArray;
}

Values not appending to my NSMutableDictionary

I'm trying to add some vales to a NSMutableDictionary dynamically. However, using the following code, I'm adding values using the first letter as the key to a temporary dictionary and then finally adding it to my names dictionary but it just overwrites each value for it's corresponding key
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
[dictionary setValue:drugStr forKey:substring];
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];
What am I doing wrong?
You should define your NSDictionary to use NSString as a key, and NSArray as a value.
Then you should just retrieve your value according to the given key. If the result is nil, then you need to create a new NSMutableArray, to which you add the value above. IF the result is not-nil, add the value to the array.
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
NSMutableArray *valueArray = (NSMutableArray*)[dictionary objectForKey:substring];
if(valueArray==nil){
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:5];
[newArray addObject:drugStr];
[dictionary setObject:newArray forKey:substring];
}else{
[valueArray addObject:drugStr];
}
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];