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);
Related
I ran into a problem and I can't find the method to get over it. basically I need to make a mutable dictionary with some values. All values are dynamic and I get them from web service or from other variables.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:comment.text forKey:#"Comment"];
[dict setObject:name.text forKey:#"Name"];
[dict setObject:[NSString stringWithFormat:#"%d",isPublic] forKey:#"VisibleForAll"];
po dict
{
Comment = "no comment";
Name = "test";
VisibleForAll = 1;
-> carts
}
Furthermore I want to add the following tree to my dictionary but I can't figure how to do this.
I have the necessary items in 2 NSArray artID and qty but I don't know how to create the bottom part so I can add it to the dict.
Carts {
Cart {
ArticleID : 22
Quantity : 1
}
Cart {
ArticleID : 45
Quantity : 3
}
...
}
I will add it with [dict setObject:carts forKey:#"Cart"] but I don't know how to add values in such a manner that I will make my dictionary on the form I presented you.
Also, don't forget that the numbers or Carts is flexible. I will get it from a Product.count.
Thanks in advance.
If your both array artID and qty have value at the same index for create a dictionary you can try like this
NSMutableArray *carts = [[NSMutableArray alloc] init];
for(NSInteger i=0; i<products.count; i++) {
//If you have custom class `cart` than use that
Cart *cart = [[Cart alloc] init];
cart.ArticleID = [[products objectAtIndex:i] valueForKey:#"pid"];
cart.Quantity = [[products objectAtIndex:i] valueForKey:#"qty"];
//If you not have any custom class than use Dictionary
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"ArticleID"];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"Quantity"];
}
Now add this carts array to Dictionary with key
[dict setObject:carts forKey:#"carts"];
NSArray *pid = [products valueForKey:#"pid" ];
NSArray *qty = [products valueForKey:#"qty"];
NSMutableArray *carts = [[NSMutableArray alloc] initWithCapacity:products.count];
for(NSInteger i=0; i<products.count; i++) {
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
NSMutableDictionary *cartemp = [[NSMutableDictionary alloc] init];
[cart setObject:[pid objectAtIndex:i] forKey:#"ArticleId"];
[cart setObject:[qty objectAtIndex:i] forKey:#"Quantity"];
[cartemp setObject:cart forKey:#"Cart"];
[carts addObject:cartemp];
}
[dict setObject:carts forKey: #"Carts"];
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];
I've a commun data in my application, and in some view I've to update those value only inside this view.
So I've created a local variable inside this view, then I set the value of those variable equal to the global variable and finally I've updated those global variable. This is my code :
if (_isCitySelector){
_dataArray = [[NSMutableArray alloc] initWithArray:[[Commun sharedInstance] stateArray]];
_subDataArray = [[NSMutableDictionary alloc] initWithDictionary:[[Commun sharedInstance] cityDictionary]];
} else {
_dataArray = [[NSMutableArray alloc] initWithArray:[[Commun sharedInstance] categoriesArray]];
_subDataArray = [[NSMutableDictionary alloc] initWithDictionary:[[Commun sharedInstance] subCategoriesDictionary]];
}
if (_activateParentSelection){
for (PFObject *object in _dataArray) {
NSMutableArray *tempArray = (NSMutableArray *)[_subDataArray valueForKey:object.objectId];
if ([[tempArray objectAtIndex:0][#"titre"] isEqualToString: #"الكل"])
continue;
PFObject *tempObject = [PFObject objectWithClassName:[object parseClassName]];
tempObject[#"titre"] = #"الكل";
if (object[#"nbrAnnonce"]){
tempObject[#"categorie_id"] = object;
tempObject[#"nbrAnnonce"] = #0;
}else
tempObject[#"region_id"] = object;
[tempArray insertObject:tempObject atIndex:0];
[_subDataArray setObject:tempArray forKey:object.objectId];
}
}
This code work's fine, but the problem this will update the global variable also ? what's wrong in my code !!!
Update
I can't use copyWithZone because my data type is PFObject and parse.com object doesn't support this function
You should try this init method for the array:
NSArray *dataArray = [[NSMutableArray alloc] initWithArray:[[Commun sharedInstance] stateArray] copyItems:YES];
This will create a separate copy of your data.
I have a strange problem because "addObject" is working to add an NSString but not to add an NSArray:
NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays
loop i times {
[starCatalogEntryData removeAllObjects];
loop j times {
[starCatalogEntryData addObject:starCatalogEntryValue]; // This works
}
[starCatalogData addObject:starCatalogEntryData]; // This does not work
}
Actually, adding the array starCatalogEntryData works but not properly. I end up with i entries in starCatalogData but they are all equal to the last value of starCatalogEntryData.
The problem is that you reuse startCatalogEntryData over and over. You want this:
NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays
loop i times {
NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
loop j times {
[starCatalogEntryData addObject:starCatalogEntryValue]; // This works
}
[starCatalogData addObject:starCatalogEntryData]; // This does not work
}
This creates a new array each time.
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];