Split array into three separate arrays - iphone

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

Related

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 retrieve all country name with counting to NSArray from NSDictionary?

Here is my dictionary result.
"continent_code" = EU;
"country_code" = gb;
"country_id" = 169;
"country_name" = "United Kingdom";
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
I want to retrieve only country name to NSArray from dictionary.
Try This ::
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];
NSLog(#" Value :: %#", [[jsonArray JSONRepresentation] JSONValue]);
for (NSDictionary *item in jsonArray) {
NSLog(#" Item :::::> %#", [item objectForKey:#"country_name"]);
}
Hope, It'll help you.
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"RootName"];
NSMutableArray *loginArray = [[NSMutableArray alloc]init];
for(int i = 0 ; i<[loginArray count];i++)
{
NSString *countryName=[[loginArray objectAtIndex:i]objectForKey:#"country_name"];
[loginArray addObject:countryName];
}
Good luck !!
The Correct Method to fill countryArray :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:yourResponseData options:kNilOptions error:&error];
NSArray* getMAS_CR = [(NSDictionary*)json objectForKey:#"yourKeyRootResult"];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
for (NSDictionary *rr in getMAS_CR)
{
NSString *cName = [NSString stringWithFormat:#"%#",[rr objectForKey:#"country_name"]];
[countryArray addObject:cName];
}
NSLog(#"countryArray :: %#",countryArray);
GoodLuck.

How to copy custom NSObject into NSMutableArray

NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSEnumerator* enumerator = [users objectEnumerator];
id element;
NSMutableArray *results;
Result *fetchedResults;
while(element = [enumerator nextObject]) {
// fetchedResults = [[Result alloc] init]; // i have tried commenting/uncommenting
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]); // this returns valid dump
}
NSLog(#"%d", [results count]); // returns 0
I don't understand wht's wrong here. I have searched through numerous tutorials and resources don't seem to get what's wrong here.
EDIT:
NSLog(#"%#", fetchedResults.name); // dumps null
You forgot to allocate your results array NSMutableArray *results = [[NSMutableArray alloc] init] this should help.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (id object in users) {
Result *fetchedResults = [[Result alloc] init];
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
}
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]);
}
NSLog(#"%d", [results count]); // returns 0

How to iterate through an NSArray containing NSDictionaries?

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.
}

NSDictionary within NSArray

A quick question about NSArrays and NDictionarys.
I have and NSArray containing NSDictionarys.
The NSDictionary contain a date and a string.
What I would like to do is end up with an NSDictionary with keys dates and values arrays of strings that are on that date.
What would be the best way to do this
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDictionary *dict in array) {
NSDate *date = [dict objectForKey:#"dateKey"];
NSString *string = [dict objectForKey:#"stringKey"];
NSMutableArray *stringsWithDate = [result objectForKey:date];
if (!stringsWithDate) {
stringsWithDate = [NSMutableArray array];
[result setObject:stringsWithDate forKey:date];
}
[stringsWithDate addObject:string];
}
Note that NSDate is not a "calendar date", so the same day with a different time will be considered as a distinct date in your result dictionary.
As I do not see any reasonable motivation for doing this, let's call it code golf.
NSMutableArray *dates = [NSMutableArray array];
NSMutableArray *strings = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
[dates addObject:[dict objectForKey:#"date"]];
[strings addObject:[dict objectForKey:#"string"]];
}
NSArray *datesArray = [[NSArray alloc] initWithArray:dates];
NSArray *stringsArray = [[NSArray alloc] initWithArray:strings];