This is my code:
NSMutableArray* notifications = [NSMutableArray arrayWithObjects:myObject.dictionary, nil];
After creating the NSMutableArray I do this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
How can I add other objects to the NSMutableArray notification?
I know I can do something like:
NSMutableArray* notifications = [NSMutableArray arrayWithObjects:object1.dictionary, object2.dictionary, object3.dictionary, nil];
but I want to add them after the creation of the NSMutableArray.
myObject contains this:
-(NSDictionary *)dictionary {
return [NSDictionary dictionaryWithObjectsAndKeys:self.name,#"name",self.category,#"category",self.note, #"note",self.dueDate, #"dueDate",self.creationDate, #"creationDate", nil];}
You can add one object as an array to an existing array as follows:
[notifications addObjectsFromArray: [NSArray arrayWithObject: object.dictionary]];
Alternatively, instead of arrayWithObject, you can also use the literal notation:
[notifications addObjectsFromArray: #[object.dictionary]];
You can add even more than one object at a time:
[notifications addObjectsFromArray: #[object1.dictionary, object2.dictionary]];
Response:
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like
NSArray =[{#"url":"productImageUrl1"},{#"url":#"ProductImageUrl2"}, nil];
productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.
I am parsing the response and able to to extract it from rsBody.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
Try this:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
for (NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
[dictURL setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[arr addObject:dictURL];
}
NSLog(#"%#", arr);
I am trying to get some keys and values from below nested JSON response. Below I have mentioned my JSON response structure, I need to get the all keys(Red, Green) and key values(Color and ID) from the below response and load into the Array for tableview cell value.
FYI: I have tried by using NSDictionary but I am getting all the time unordered values. I need to get ordered values also. Please help me!
{
response: {
RED: {
Color: "red",
color_id: "01",
},
GREEN: {
Color: "green",
color_id: "02",
}
},
Colorcode: { },
totalcolor: "122"
}
My Code:
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
NSLog("%#",[responsData objectAtIndex:0]); // here I am getting bad exception
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
I have create JSON data through coding so don't consider it just check the following answer
/// Create dictionary from following code
/// it just for input as like your code
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary * innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"red" forKey:#"Color"];
[innr setObject:#"01" forKey:#"color_id"];
NSMutableDictionary * outer = [[NSMutableDictionary alloc] init];
[outer setObject:innr forKey:#"RED"];
innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"green" forKey:#"Color"];
[innr setObject:#"02" forKey:#"color_id"];
[outer setObject:innr forKey:#"GREEN"];
[dict setObject:outer forKey:#"response"];
// ANS ------ as follow
// get keys from response dictionary
NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[dict[#"response"] allKeys]];
// sort as asending order
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: YES];
key = (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
// access inner data from dictonary
for (NSString * obj in key) {
NSLog(#"%#",dict[#"response"][obj][#"Color"]);
NSLog(#"%#",dict[#"response"][obj][#"color_id"]);
}
I think you want same and it will help you!
If you're stuck with this JSON, if you want an array of the values, you can do the following:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *response = json[#"response"];
NSArray *colors = [response allValues];
If you need that array of colors sorted by color_id, for example, you can sort that yourself:
NSArray *sortedColors = [colors sortedArrayUsingDescriptors:#[[[NSSortDescriptor alloc] initWithKey:#"color_id" ascending:TRUE]]];
When I try to print array of json values in log, I get addresses instead of values. Here's how I coded.
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSMutableArray *anotherTempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSDictionary *dict;
for(dict in jsonArray)
{
NSString *projectName = dict[#"Name"];
NSString *urlText = dict[#"Url"];
NSLog(#"Url text in array = %#", urlText);
NSString *attch = dict[#"attachmentes"];
NSLog(#"Attached url in array = %#", attch);
NSString *projID = dict[#"ProjectID"];
NSLog(#"Project ID in array = %#", projID);
SaveAttachment *saveAt = [[SaveAttachment alloc] initWithName:projectName withList:#"View" withAttachment:#"View"];
[tempArray addObject:saveAt];
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
}
array = tempArray;
[self.tableViewProject reloadData];
NSLog(#"Array of project IDs === %#", anotherTempArray); //Get values (array of project ids here.
}
Replace
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
with
[anotherTempArray addObject:projID];
This is because your anotherTempArray contains objects of SaveProjectId ie, everytime in for loop you are adding saveProj object not projID. Thats why your array showing SaveProjectId objects.
If you want to directly save them, then use the below modification
[anotherTempArray addObject:projID];
or you can use like(this is i would prefer)
NSLog(#"First project ID === %#", [anotherTempArray objectAtindex:0] projectId]);
You are storing SaveProjectId objects in the array, therefore when you print the content you see the address of those objects.
your "anotherTemoArray" is having objects of SaveProbectId so you have to pass object at index to SaveProjectId and then you can see the array information
When calling NSLog(#"Array of project IDs === %#", anotherTempArray); the -(NSString*)description method on each of the objects inside 'anotherTempArray' is being called.
In your case that means -(NSString*)description is being called on SaveProjectId objects. Override it to print out what you want... e.g.
-(NSString*)description {
return [NSString stringWithFormat:#"SaveProjectId: %#",self.projectId];
}
I am new to iOS and want to create an NSArray like this which contains an NSDictionary.
[
{
Image: 1, 2,3
Title: 1,2,3
Subtitle:1,2,3
}
]
I have tried this.
NSArray *obj-image=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *obj-title=#[#"Test",#"Test",#"Test"];
NSArray *obj-subtitle=#[#"Test",#"Test",#"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];
But not working and how to access them.
First of all, you initialization of Arrays and Dictionaries is wrong. You cannot use "-" in the names, period.
Second, you need to allocate and then initialize the objects. This is how you do that with arrays:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
Then you need Mutable dictionary and mutable arrays to work with the data (mutable means you can change the values inside, add or remove objects etc.)
This is the most basic example of what you are trying to achieve:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
NSMutableArray *objectsMutable = [[NSMutableArray alloc] init];
for (NSString *string in images) {
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc] init];
[dictMutable setObject:string forKey:#"image"];
//determining the index of the image
NSInteger stringIndex = [images indexOfObject:string];
[dictMutable setObject:[titles objectAtIndex:stringIndex] forKey:#"title"];
[dictMutable setObject:[subtitles objectAtIndex:stringIndex] forKey:#"subtitle"];
NSDictionary *dict = [[NSDictionary alloc] init];
dict = dictMutable;
[objectsMutable addObject:dict];
}
NSArray *objects = objectsMutable;
NSLog(#"%#", objects);
Hope this helps.
As you can see, I'm going through the images array, capturing the index of each one, an then just apply values of other arrays from the same index into a mutable dictionary.
All I do after that is just make a regular dictionary and array to put the data inside. This is ho the Log will look:
(
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
}
)
You have an array with three objects inside, each with their own image, title and subtitle.
Here is code :
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *mdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"object1",#"key1",#"object2",#"key2",nil];
[array addObject:mDict];
so now if u need to access dictionary from array then :
NSMutableDictionary *mDict1 = [array objectatindex:0];
NSLog(#"%#",[mDict1 valueForkey:#"key1"];
--> print object 1.
This is the way to store array of dictionaries:
NSDictionary *dic=#{#"kishore":#"hai"};
NSMutableArray *arr=[[NSMutableArray alloc]init];
[arr addobject:dic];
this is the way to get those values:
[arr objectforkeyValue #"kishore"];
NSMutableArray *dictArray = [[NSMutableArray alloc] init]; // created and initiated mutable array
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // created and initiated mutable Dictionary
[dict setObject:#"object1" forKey:#"1"]; // added a key pair in dictionary (you can set multiple objects)
[dictArray addObject:dict]; // added dictionary to array (you can add multiple dictionary to array )
NSLog(#"dictionary inside an array : %#",dictArray[0][#"1"]); // access dictionary from array
You can try something like this
[NSArray arrayWithObjects:#{#"Image":#[#1,#2,#3]},#{#"Title":#[#1,#2,#3]},#{#"SubTitle":#[#1,#2,#3]}, nil];
You can easily create objects of array and access them back using following way.
NSArray *objimage=#[#"Test1.png",#"Test2.png",#"Test3.png"];
NSArray *objtitle=#[#"Test1",#"Test2",#"Test3"];
NSArray *objsubtitle=#[#"Test1",#"Test2",#"Test3"];
NSDictionary *obj_dictionary = #{#"image":objimage,#"Title":objtitle, #"subtitle":objsubtitle};
NSArray * obj_array= [[NSArray alloc] initWithObjects:obj_dictionary, nil]; // Create Array of nested objects
if([obj_array count] > 0) {
NSArray * imageArray = obj_array[0][#"image"]; // Access the nested objects in Array.
NSLog(#"%#", imageArray[0]);
}
first of all u need to declare correct variable name
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
at this point all u are created all the array, and u need to create dictionary like below
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this
in above obj_dictionary will contains all the array like below,
Title = (
Test,
Test,
Test
);
image = (
"Test.png",
"Test.png",
"Test.png"
);
subtitle = (
Test,
Test,
Test
);
and u can access the object in the dictionary like below using a key for example
NSArray * obj_array_images = obj_dictionary[#"image"];
gives an array of images that is associated with key image, similarly u can access other array like this by providing different keys associated with the dictionary obj_dictionary for example
NSArray * obj_array_titles = obj_dictionary[#"title"];
NSArray * obj_array_subtitles = obj_dictionary[#"subtitle"];
edit
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this