Adding objects to instance variable array - ios

Can someone help me out on this:
Im creating a property in my TableVC.m file :
#property NSMutableArray *savingBeaconSpecs;
In my Viewdidload I instantiate the array:
NSMutableArray *savingBeaconSpecs = [[NSMutableArray alloc]init];
Now I do requests to the server, and I want to save the returned JSON into objects and save these each time in the array. So I did the following in the ConnectionDidFinishLaunching:
self.artworkArray = [NSJSONSerialization JSONObjectWithData:self.data options:0 error:&err];
NSLog(#"Log ArtworkArray in ConnectionDidFinishLoading%#", self.artworkArray);
And:
Artwork *artwork = [[Artwork alloc]init];
artwork.title = [self.artworkArray valueForKey:#"name"];
artwork.artist = [[self.artworkArray objectForKey:#"artist"] valueForKey:#"name"];
artwork.CreationYear = [self.artworkArray valueForKey:#"creationYear"];
artwork.categorie = [[self.artworkArray objectForKey:#"exposition"] valueForKey:#"name"];
Now I want to save this object into the savingBeaconSpecs NSMutableArray
[self.savingBeaconSpecs addObject:artwork];
But the NSMUtableArray savingBeaconSpecs always returns 0 when i try log his content
Anyone please?

Because you declare it locally in your viewDidLoad :
NSMutableArray *savingBeaconSpecs = [[NSMutableArray alloc]init];
you should use
self.savingBeaconSpecs = [[NSMutableArray alloc]init];
and
[self.savingBeaconSpecs addObject:artwork];
and declare your property as (without the first capital S)
#property NSMutableArray *savingBeaconSpecs;

To instantiate the array, you should do:
self.savingBeaconSpecs = [[NSMutableArray alloc] init];
or equally good:
self.savingBeaconSpecs = [NSMutableArray array];

Related

why adding string to NSMutableArray not work?

why adding string to nsmuarray not work?
firstly, i add the a NSDictionary by keypath to the NSMutableArray,
its work.
after that i want to add one more string to that but its not work.
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:#"groupid"];
until now everything work.
[_joinornot addObject:#"111"];<----unrecongnized selector sent to instance
if _joinornot = [tempobject valueForKeyPath:#"groupid"]; returns nil, then your array will be nil, and then you cant call addObject. so maybe add a nil check
Looks like "_joinornot" it's not an NSMutableArray or NSMutable data type, try to see what kind of object it is:
NSLog(#"%#", [_joinornot class]);
If it is not a subclass of Mutable type you can't add objects to him.
Try below code:
Before adding object just check for nil.
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:#"groupid"];
if (_joinornot==nil) {
_joinornot = [[NSMutableArray alloc] init];
[_joinornot addObject:#"111"];
}
else{
[_joinornot addObject:#"111"];
}
Edit:
May be it's converted to NSArray so it will be no more mutable, try with
_joinornot = [[tempobject valueForKeyPath:#"groupid"] mutableCopy];

NSMutableArray and addObject - Sublist

How can I have sub lists using NSMutableArray and addObject:
Here is the current code:
categories = [[NSMutableArray alloc] init];
[categories addObject:#"Line 1"];
[categories addObject:#"Line 2"];
[categories addObject:#"Line 3"];
[categories addObject:#"Line 4"];
I would like to have sublisting like so:
Line 1
Line A
Line B
Line C
Line 2
Line A
Line B
Line C
...etc...
Let me know if this is possible and how. Thanks.
You're just adding strings to an array. If you want a list within a list, you have to create the sublist and then add it as an object within the main list
NSMutableArray *mainList = [NSMutableArray new];
NSArray *subList = #[#"thing 1",#"thing 2",#"thing 3"];
[mainList addObject:subList];
Then, if you want to access and individual subArray, you could do so like this:
NSArray *subList = mainList[0];
Or an individual sublist item:
NSString *item = mainList[0][1];
Which would be the second item in the first sublist.
You need to create an object, let's say MyObject, which contains a string and another Array
#interface MyObject
#property NSString *name;
#property NSMutableArray *items;
#end
and add MyObject objects to your categories array.
you can do it like this:
NSMutableArray *categories = [[NSMutableArray alloc] init];
NSArray *LineOne = #[#"Line A",#"Line B",#"Line C"];
NSArray *LineTwo = #[#"Line A",#"Line B",#"Line C"];
[categories addObject:LineOne];
[categories addObject:LineTwo];
Looks like NSMutableDictionary is your solution:
NSMutableDictionary * dict = [NSMutableDictionary new];
NSArray *line1list, *line2list, *line3list;
// init list arrays
[dict setObject:line1list forKey:#"Line 1"];
[dict setObject:line2list forKey:#"Line 2"];
[dict setObject:line3list forKey:#"Line 3"];

Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary

I'm getting data from SQL server in following variables in one class:
#property(retain,nonatomic) NSString* trainingName;
#property(retain,nonatomic) NSNumber* trainingCount;
In other class,I want to append this value in NSMutableArray and finally make a dictonary.I'm doing this as following:
-(void)getTrainingDetails
{
MyTestSp_GetTrainingCountsList *objReturnTrainings = [MyTestSp_GetTrainingCounts findAll];
NSMutableArray *trainingNames = [[NSMutableArray alloc]init];
NSMutableArray *trainingCounts = [[NSMutableArray alloc]init];
NSMutableDictionary *dictTrainings = [[NSMutableDictionary alloc]init];
if ([objReturnTrainings length] > 0)
{
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
// get the values and assign to NSMutable array
trainingNames = trainingName;
trainingCounts = trainingCount;
//Make the dictionary.
}
}
}
Is this the correct way of doing and how can I put this in dictionary?
Please help.
You appear to be trying to set your array directly to your number / string (which you aren't actually getting out of obj so your code shouldn't compile...). You also don't need the arrays to create the dictionary. You can just do:
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
dictTrainings[obj.trainingName] = obj.trainingCount;
}

How to initialize an empty mutable array in Objective C

I have a list of objects (trucks) with various attributes that populate a tableview. When you tap them they go to an individual truck page. There is an add button which will add them to the favorite list in another tableview. How do I initialize an empty mutable array in Cocoa?
I have the following code:
-(IBAction)addTruckToFavorites:(id)sender:(FavoritesViewController *)controller
{
[controller.listOfTrucks addObject: ((Truck_Tracker_AppAppDelegate *)[UIApplication sharedApplication].delegate).selectedTruck];
}
Update:
With new syntax you can use:
NSMutableArray *myArray = [NSMutableArray new];
Original answer:
for example:
NSMutableArray *myArray = [[NSMutableArray alloc] init];
And here you find out why (difference between class and instance method)
Basically, there are three options:
First
NSMutableArray *myMutableArray = [[NSMutableArray alloc] init];
Second
NSMutableArray *myMutableArray = [NSMutableArray new];
Third
NSMutableArray *myMutableArray = [NSMutableArray array];
You can also initialize in this way
Another way for Objective C apart from the answer of #NSSam
NSMutableArray *myMutableArray = [#[] mutableCopy];
For Swift
let myArray = NSMutableArray()
OR
let myArray = [].mutableCopy() as! NSMutableArray;
NSMutableArray *arr = [NSMutableArray array];
I use this way to initialize an empty mutable array in Objective C:
NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
listOfTrucks = [NSMutableArray array]; gives you a new mutable array.
In modern Objective - C it could be even more shorter:
NSArray *array = #[];

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