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];
Related
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];
I am very new to Objective-C and iOS programming so be gentle :)
I am trying to add an nsmutabledictionary to and nsmutablearray. I am succeeding but not with the results I was hoping for. Here is my code :
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary setValue:#"lat2" forKey:#"lat"];
[dictionary setValue:#"long2" forKey:#"long"];
[dictionary setValue:#"alt2" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
Here is the NSLog output:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
Here is what I was hoping to achieve:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt1;
lat = lat1;
long = long1;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
If I the dictionary straight to the array (instead of add the dictionary to messages and then adding that to the array) then I get the output I am looking for. Can somebody explain to me exactly what I am doing wrong?
It looks to me like you want:
An array
At index 0:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
At index 1:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
The data in the second array entry should use the same keys, but different data. As the others have pointed out, your mistake is using a single dictionary "dictionary"
When you add an object to a collection like a dictionary or array, the collection holds a pointer to the object, not a copy of the object. If you add the same object to a collection more than once, you have 2 pointers to the same object, not 2 unique objects.
When you add your "dictionary" object, to your structure, change it, and add it again, you are not getting the result you expect because both entries in your structure point to a single dictionary. When you change the values, it changes in both places.
The same goes for your "messages" dictionary. You need 2 of those as well.
Fix your code by adding new dictionaries, dictionary2 and messages2:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages2 = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary2 setValue:#"lat2" forKey:#"lat"];
[dictionary2 setValue:#"long2" forKey:#"long"];
[dictionary2 setValue:#"alt2" forKey:#"alt"];
[messages2 setObject: dictionary2 forKey:#"messages"];
[array addObject: messages2];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
You might also look at using object literal syntax, e.g.:
dictionary[#"lat"] = #"lat1";
dictionary[#"long"] = #"long1";
dictionary[#"alt"] = #"alt1";
messages[#"messages"] = dictionary;
If you didn't need the whole thing to be mutable, you could even do everything with one line:
NSMutableArray *array = [
#[
#{#"messages": #{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"}},
#{#"messages": #{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"}}
];
Or to make it mutable:
NSMutableArray *array = [
#[
[#{#"messages":
[#{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"} mutableCopy]} mutableCopy],
[#{#"messages":
[#{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"} mutableCopy]} mutableCopy]
] mutableCopy];
EDIT: to add contents dynamically, you could use a method like this: (assuming that array is an instance variable)
- (void) addMessageWithLat: (NSString *) latString
long: (NSString *) longString
alt: (NSString *) altString;
{
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSDictonary *contents =
[#{#"lat": latString,
#"long": longString,
#"alt": altString}
mutableCopy];
messages[#"messages"] = contents;
[array addObject: messages];
}
The problem is that you are making adding the new values in the same object reference. So the new Value will replace the older one. Just add this line before [dictionary setValue:#"lat2" forKey:#"lat"];
dictionary = [NSMutableDictionary alloc]init];
and this line before the second instance of [messages setObject:dictionary forKey:#"messages"];
messages = [[NSMutableDictionary alloc] init];
I am trying to store an array in a NSMutableDictionary. However the NSMutableDictionary is null after i have set objects to it. Here is my code any help is appreciated:
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableDictionary *dTemp = [[NSMutableDictionary alloc] init];
STStockData *stockData = [[STStockData alloc] init];
for (int i = 0; i < [_arrTickers count]; i++) {
// get the ticker from its json form
dTemp = [_arrTickers objectAtIndex:i];
NSLog(#"Ticker: %#",[dTemp objectForKey:#"ticker"]);
// gets current data for ticker
[arrTemp addObjectsFromArray:[stockData getCurrentStockDataForTicker:[dTemp objectForKey:#"ticker"]]];
NSLog(#"Price %#",[arrTemp objectAtIndex:1]); // just to prove the array isnt nil.
// adds it to the dictionary
[_dStockData setObject:arrTemp forKey:[dTemp objectForKey:#"ticker"]];
NSLog(#"Dictionary %#",_dStockData);
// remove all objects so can reuse.
[arrTemp removeAllObjects];
dTemp = nil; // can't remove objects using [removeAllObjects] method. believe its due to it holding inside NSArrays which are immutable.
}
Here is the console output:
Initialize _dStockData
_dStockData = [[NSMutableDictionary alloc] init];
It is nil because use initialize stockData
STStockData *stockData = [[STStockData alloc] init];
and print _dStockData
NSLog(#"Dictionary %#",_dStockData);
I have created a plist file that looks like this:
From this is am able to extract all plist info into an NSArray:
-(NSArray *)Topics
{
if(!_Topics)
{
_Topics = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"TopicData" ofType:#"plist"]];
}
return _Topics;
}
And use this array to load a tableview of TopicTitle's:
cell.textLabel.text = [[self.Topics objectAtIndex:indexPath.row] valueForKey:#"TopicTitle"];
When a row in the table is selected, I am passing the dictionary named 'Questions' to the next ViewController like this:
NSDictionary *questions = [[self.Topics objectAtIndex:indexPath.row] valueForKey:#"Questions"];
[self.detailViewController setQuestions:(questions)];
From here I want to loop through each 'Question' dictionary and load the 'QuestionText' and 'AnswerOne / Two...' strings into an array of objects by doing something like this:
TopicQuestions = [NSMutableArray array];
for(NSDictionary *ques in self.Questions)
{
Question* q = [[Question alloc] init];
q.Question = (NSString*)[ques objectForKey:#"QuestionText"];
q.AnswerOne = (NSString*)[ques objectForKey:#"QuestionText"];
q.AnswerTwo = (NSString*)[ques objectForKey:#"QuestionText"];
q.AnswerThree = (NSString*)[ques objectForKey:#"QuestionText"];
q.AnswerFour = (NSString*)[ques objectForKey:#"QuestionText"];
[TopicQuestions addObject:q];
}
But the 'Questions' dictionary does not seem to have this data available, it knows there are 4 child objects, but does not have all the key - pair values of these objects:
So my question is how should I pass the 'Questions' dictionary to the next ViewController so that I will still be able to access the 'QuestionText' and 'AnswerOne / Two...' nodes?
Or is there a better way of reading the strings without looping through each 'Question' dictionary?
I don't think you are getting the question dictionary properly. In your screenshot the ques object is an NSString object, not an NSDictionary. So getting objectForKey on the NSString object ques is not going to work (and really should crash your app).
Try this for loop:
for(NSString *ques in self.Questions)
{
NSDictionary *dict = [self.questions objectForKey:ques];
Question* q = [[Question alloc] init];
q.Question = (NSString*)[dict objectForKey:#"QuestionText"];
q.AnswerOne = (NSString*)[dict objectForKey:#"QuestionText"];
q.AnswerTwo = (NSString*)[dict objectForKey:#"QuestionText"];
q.AnswerThree = (NSString*)[dict objectForKey:#"QuestionText"];
q.AnswerFour = (NSString*)[dict objectForKey:#"QuestionText"];
[TopicQuestions addObject:q];
}
I am using NSMutableDictionary. Declare it using property as follows:
#property (strong, nonatomic) NSMutableDictionary *books;
In the method, I am assigning it values.
- (void)setUpBooks {
if (self.books == nil){
self.books = [[NSMutableDictionary alloc] init];
}
// my code goes here...
[self.books setObject:book forKey:key];
NSLog(#"books : %#",self.books);
NSLog(#"books Count : %d",[self.books count]);
}
In this NSLog it's showing correct values. But when I tried to use self.books in another method its showing null. I don't know where my data is losing.
Easy way to use NSMutableDictionay.
Try this,
NSMutableDictionary * books = [[NSMutableDictionary alloc] init];
NSDictionary *book = [[NSDictionary alloc] initWithObjectsAndKeys:#"Value",#"BOOK_KEY", nil];
[books addEntriesFromDictionary:book];
Hope it's help you.