Add an object to a NSMutableArray using arrayWithObject - ios

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

Related

Add other object to NSArray

I made a small code
NSArray* _options = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[UIImage imageNamed:#"2"],#"img",name,#"text"
, nil],nil];
Now, I want add other object to _options. What should i do?
I make more test but no success.
Thank for all
you can use [NSArray arrayByAddingObject:]
_options = [_options arrayByAddingObject:object];
or change _options to NSMutableArray
NSMutableArray *_options = [NSMutableArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[UIImage imageNamed:#"2"],#"img",name,#"text"
, nil],nil];
[_options addObject:object];
and you may want to use modern syntax
NSMutableArray *_options = [#[#{#"img":[UIImage imageNamed:#"2"],#"text":name}] mutableCopy];
[_options addObject:object];
NSArray does not allow any changes to be made; you can use an NSMutableArray instead like this:
NSMutableArray *mutable = [_options mutableCopy];
[mutable addObject:yourObject];
NSDictionary is same in that it can't be mutated.
You can't add objects to a NSArray, to do so, you need a NSMutableArray.
However, you can add objects to NSArray when creating it with : arrayWithObjects
First, create an NSMutableArray, as you can make changes to it as you see fit later throughout your code:
NSMutableArray *newOptions = [NSMutableArray alloc]init];
[newOptions setArray:_options];
[newOptions addObject:yourObject];

How to get array of values from NSDictionary array

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

how to add JSON data to an NSArray

I have json data as below.
[
{"id":"2","imagePath":"image002.jpg","enDesc":"Nice Image 2"},
{"id":"1","imagePath":"image001.jpg","enDesc":"Nice Image 1"}
]
I am assigning this to variable named NSArray *news.
Now I have three different array as below.
NSArray *idArray;
NSArray *pathArray;
NSArray *descArray;
I want to assign data of news to these arrays so that finally I should have as below.
NSArray *idArray = #["2","1"];
NSArray *pathArray = #["image002.jpg","image001.jpg"];
NSArray *descArray = #["Nice Image 2","Nice Image 1"];
Any idea how to get this done?
With the help of below answer this is what I did.
pathArray = [[NSArray alloc] initWithArray:[news valueForKey:#"imagePath"]];
I don't wanted to use NSMutableArray for some reasons.
You should use JSONKit or TouchJSON to convert your JSON data to Dictionary.
Than you may do this :
NSArray *idArray = [dictionary valueForKeyPath:#"id"]; // KVO
Use this
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
then you can extract all the information that you need from there you have NSArray that contains NSDictionary , where you can go and use objectForKey: to get all the info you need.
Load the json data into an NSDictionary, which you may call "news" . Then retrieve as
NSArray *idArray = [news valueForKeyPath:#"id"];
NSArray *pathArray = [news valueForKeyPath:#"imagePath"];
NSArray *descArray = [news valueForKeyPath:#"enDesc"];
Yes all the above ans is correct I am just integrating all of them together to be easly use to you:
NSArray *serverResponseArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil]; // I am assigning this json object to an array because as i show it is in array format.
now:
NSArray *idArray = [[NSMutableArray alloc] init];
NSArray *pathArray = [[NSMutableArray alloc] init];
NSArray *descArray = [[NSMutableArray alloc] init];
for(NSDictionary *news in serverResponseArray)
{
[idArray addObject:[news valueForKey:#"id"]];
[pathArray addObject:[news valueForKey:#"imagePath"]];
[descArray addObject:[news valueForKey:#"enDesc"]];
}

NSArray add objects from other array

I have three NSArray objects. I need to add all objects for this array to NSArray that is called allMyObjects.
Have NSArray standard solution to make it for example via initialization method or do I need make custom method to retrieve all objects from other arrays and put all retrieved objects to my allMyObjects array?
Don't know if this counts as a sufficiently simple solution to your problem, but this is the straight forward way to do it (as alluded to by other answerers, too):
NSMutableArray *allMyObjects = [NSMutableArray arrayWithArray: array1];
[allMyObjects addObjectsFromArray: array2];
[allMyObjects addObjectsFromArray: array3];
once see this one ,
NSArray *newArray=[[NSArray alloc]initWithObjects:#"hi",#"how",#"are",#"you",nil];
NSArray *newArray1=[[NSArray alloc]initWithObjects:#"hello",nil];
NSArray *newArray2=[[NSArray alloc]initWithObjects:newArray,newArray1,nil];
NSString *str=[newArray2 componentsJoinedByString:#","];
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"()\n "];
str = [[str componentsSeparatedByCharactersInSet:doNotWant] componentsJoinedByString: #""];
NSArray *resultArray=[str componentsSeparatedByString:#","];
NSLog(#"%#",resultArray);
O/P:-
(
hi,
how,
are,
you,
hello
)
You can call addObjectsFromArray: method on your allMyObjects array.
Here am adding code for store and get datas from array to array.
To store array to array
NSMutableArray rowOneRoundData = [NSMutableArray arrayWithObjects: #"45",#"29",#"12",nil];
NSMutableArray rowTwoRoundData = [NSMutableArray arrayWithObjects: #"41",#"45",#"45",nil];
NSMutableArray rowThreeRoundData = [NSMutableArray arrayWithObjects: #"12",#"45",#"22",nil];
NSMutableArray rowFourRoundData = [NSMutableArray arrayWithObjects: #"45",#"12",#"61",nil];
NSMutableArray rowFiveRoundData = [NSMutableArray arrayWithObjects: #"12",#"14",#"14",nil];
NSMutableArray rowSixRoundData = [NSMutableArray arrayWithObjects: #"12",#"12",#"12",nil];
NSMutableArray rowSevenRoundData = [NSMutableArray arrayWithObjects: #"12",#"36",#"83",nil];
NSMutableArray rowEightRoundData = [NSMutableArray arrayWithObjects: #"37",#"57",#"45",nil];
NSMutableArray rowNineRoundData = [NSMutableArray arrayWithObjects: #"12",#"93",#"83",nil];
NSMutableArray rowTenRoundData = [NSMutableArray arrayWithObjects: #"16",#"16",#"16",nil];
NSArray circleArray = [[NSArray alloc]initWithObjects:rowOneRoundData,rowTwoRoundData,rowThreeRoundData,rowFourRoundData,rowFiveRoundData,rowSixRoundData,rowSevenRoundData,rowEightRoundData,rowNineRoundData,rowTenRoundData, nil];
Get data from Circle Array
for (int i= 0; i<10;i++)
{
NSArray *retriveArrar = [[circleArray objectAtIndex:i] mutableCopy];
}

How to create NSDictionary inside NSArray and How to access them in ios

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

Resources