Populating NSmutableDictionary error - ios

Greeting. I have a NSmutableDictionary and want to populate it.
- (IBAction)addCourse:(UIButton *)sender {
//NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
//To add content and keys
NSInteger numRow=[picker selectedRowInComponent:kNumComponent];//0=1st,1=2nd,etc
NSInteger SeaRow=[picker selectedRowInComponent:kSeaComponent];//0=fall,1=spring,2=summer
NSInteger CourseRow=[picker selectedRowInComponent:kCourseComponent];
NSString *num=Number[numRow];
NSString *season=Season[SeaRow];
NSString *course=Course[CourseRow];
NSString *AddKey=[NSString stringWithFormat:#"%# %#",num,season];
[contents setObject:[NSMutableArray arrayWithObjects:course, nil] forKey:AddKey];
// NSLog(#"%#", key);//test key here, it works
NSLog(#"Dictionary: %#", [contents description]);//test dictionary here
...}
Here, I have a button, when I push it, num and season and form a key, and the related course will be add to the dictionary. However, when I test it with
NSLog(#"Dictionary: %#", [contents description]);
to show all the content in the dictionary, Only the last record in my selection is shown. In other words, when populating the dictionary, the previous data were override by the later one. What is the problem please?
Update: Thanks for Javier's advice. It fix this problem. But now in the new situation, only one key can hold one content. The following content will override the old one, why is that please?

NSMutableDictionary *contents is not retained by any object of your controller and when the method finishes, that object will be released automatically .
Try declaring contents as a property:
#property (nonatomic,strong) NSMutableDictionary *contents;

Related

NSMutableArray is affecting the another NSMutableArray?

I have two NSMutableArrays, both getting the same data. My problem is that when I assign the same data to both the mutable arrays from different dictionaries and perform operations on one NSMutableArray, it is affecting both arrays.
When I perform operations like replaceObjectAtIndex:WithObject:, the first time, the array is not affected but when the second replace is called both arrays have the replaced value. I think it is a reference issue.
Does anyone have a solution to this?
Name of the NSMutableArrays is helper.urlsRecording and helper.holdingArr.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict setValue:outputFileURL forKey:#"URL"];
[dict setValue:#"1" forKey:#"index"];
[dict2 setValue:outputFileURL forKey:#"URL"];
[dict2 setValue:#"1" forKey:#"index"];
[helper.urlsRecording addObject:dict];
[helper.holdingArr addObject:dict2];
[helper.urlsRecording replaceObjectAtIndex:button.tag withObject:urlAr];//When this called second time, both the arrays is effected(helper.urlsRecording as well as helper.holdingArr).
How can I prevent the copying of the reference to another array?
Button Click:
if([button isSelected] == NO){
NSLog(#"Url Recording : %#",helper.urlsRecording);
[[helper.urlsRecording objectAtIndex:button.tag] removeObjectForKey:#"URL"];
button.selected = YES;
NSLog(#"Url Recording : %#",helper.urlsRecording);
}
else{
[helper.urlsRecording replaceObjectAtIndex:button.tag withObject:[helper.holdingArr objectAtIndex:button.tag]];
button.selected = NO;
NSLog(#"Url Recording : %#",helper.urlsRecording);
}
Note: NSMutableArray is defined globally in a class to access.
This is because your instance values are same for both dictionary.
So First create one mutableDictionary like below
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:outputFileURL forKey:#"URL"];
[dict setValue:#"1" forKey:#"index"];
And create second dictionary through mutableCopy, so instance will be different for both.
NSMutableDictionary *dict2 = [dict mutableCopy];
After that you can add them in to NSMutableArray and update accordingly.
Take a copy/mutableCopy dictionary & then add object to the MutableArray
[helper.urlsRecording addObject:[dict copy]];
[helper.holdingArr addObject:[dict2 copy]];

Crash with a loop which look in a mutable array [duplicate]

I have the following situation where
I have an NSMutableArray filled with an xml file which I want to search.
When I enter something in the search field I get this Error:
-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x5b388b0
What does it means and how can I fix it??
I suppose the error is somewhere around here.
- (void)searchTableView{
searchedList = [[NSMutableArray alloc] init];
NSLog(#"new list %#", searchedList);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in list) {
NSArray *array = [dictionary objectForKey:#"TITLE"];
[searchArray addObjectsFromArray:array];
}
for (NSString *TempArray in searchArray) {
NSRange titleResults = [TempArray rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResults.length > 0)
[searchedList addObject:TempArray];
}
[searchArray release];
searchArray = nil;
}
it means you are calling a method designed for an NSArray (countByEnumeratingWithState:objects:count on a NSString.
I don't know ifthis code is copy/paste from yours, but if so, at the end where you use [searchList addObject:TempArray] you don't have an object named searchList.
Also, work on your naming conventions. big time.

Combining dictionaries: No class method for selector "addEntriesFromDictionary"

I am struggling with a dictionary in which I want to create a new dictionary from a series of keys (P, SP, and RP).
I have attempted to create a new NSMutableDictionary that combines individual Dictionaries that have have all the values for the P, SP, and RP keys respectively, but have gotten the error "No class method for selector "addEntriesFromDictionary" "
Here is my code:
NSMutableDictionary *newDict = [NSMutableDictionary addEntriesFromDictionary:self.allSPPositions];
and
#interface className ()
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
#end
#implementation className
- (void)viewDidLoad {
Any help or insight would be appreciated! Thanks!
The compiler is telling you exactly what's wrong. You're trying to add items from a dictionary to the NSMutableDictionary class. You need to send the ad items from dictionary message to an instance of NSMutableDictionary.
This line:
NSMutableDictionary *newDict =
[NSMutableDictionary addEntriesFromDictionary:self.allSPPositions];
Should read
NSMutableDictionary *newDict =
[someDictionary addEntriesFromDictionary: self.allSPPositions];
(Where someDictionary is the dictionary to which you want to add items.)
or even
NSUInteger count = [self.allSPPositions count];
NSMutableDictionary *newDict =
[NSMutableDictionary dictonaryWithCapacity: count];
[newDict addEntriesFromDictionary: self.allSPPositions];
(Since your code appears to be trying to create a new, mutable dictionary and add the contents of self.allSPPositions.)
If your goal is to get a mutable copy of self.allSPPositions, there is a cleaner way to do that:
NSMutableDictionary *mutablePositions = [self.allSPPositions mutableCopy];
Uhh, here's an example that will compile and use the method in question, you should probably NOT call that method in your Interface since it's part of Apple's framework and is already predefined, unless you have a special reason for doing so:
NSMutableDictionary *dict =[[NSMutableDictionary alloc] init];
[dict setValue:#"Seattle" forKey:#"name"];
[dict setObject:[NSNumber numberWithInt:3] forKey:#"age"];
[dict setObject:[NSDate date] forKey:#"date"];
dict[#"city"]=#"Seattle";
[dict addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys: #"Washington",#"location", nil]];
This is merely meant to get you started, but it shows you how to do this so that it works for you in your circumstances

Getting NSmutableDictionary key from two mutable arrays

I have three mutable arrays
#interface PickeriviewAndTableViewController ()
//Create mutableArray for tableView
#property(strong,nonatomic)NSMutableArray *msgYear;
#property(strong,nonatomic)NSMutableArray *msgSeason;
#property(strong,nonatomic)NSMutableArray *msgCourse;
I want to add element to array msgCourse[ ] using the key generating from the first two arrays msgYear[ ] and msgSeason[ ].
Then I want to populate the msgCourse[] array using a button
- (IBAction)addCourse:(UIButton *)sender {
//To get value from pickerView, prepare for key and contents
NSInteger numRow=[picker selectedRowInComponent:kNumComponent];//0=1st,1=2nd,etc
NSInteger SeaRow=[picker selectedRowInComponent:kSeaComponent];//0=fall,1=spring,2=summer
NSInteger CourseRow=[picker selectedRowInComponent:kCourseComponent];
NSString *num=Number[numRow];
NSString *season=Season[SeaRow];
NSString *course=Course[CourseRow];
NSString *CourseToAdd=[[NSString alloc ]initWithFormat:#"%# ",course];
NSString *SeasonToAdd=[[NSString alloc ]initWithFormat:#"%# ",season];
NSString *YearToAdd=[[NSString alloc ]initWithFormat:#"%# ",num];
// Try to generate key from YearToAdd and SeasonToAdd and fill in content
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *keyFromYearAndSeason = #"Don't_know_what_to_do_here";
[contents setObject:[NSArray arrayWithObjects:#"Don't_know_how", nil] forKey:keyFromYearAndSeason];
[keys addObject:keyFromYearAndSeason];
[self setSectionKeys:keys];
[self setSectionContents:contents];
}
My question is: How to complete my code by replacing these "Don't know how" lines of code here please?
Update: To be more clear, key is generating from msgYear[ ] and msgSeason[ ] e.g. '2001 fall', dictionary is filled with course e.g. 'chemistry','math'.
The link to your other question helped provide context for what you are trying to achieve.
You don't need to create a dictionary or an array inside the addButtton method - you should have your dictionary as a property that is already initialised.
Then, in add button you retrieve the array associated with the key - if the value is nil then you create a new array and put the course in. If the value isn't nil simply add the course to the array.
#property (strong,nonatomic) NSMutableDictionary *tableEntries; // alloc/init this in viewDidLoad
- (IBAction)addCourse:(UIButton *)sender {
//To get value from pickerView, prepare for key and contents
NSInteger numRow=[picker selectedRowInComponent:kNumComponent];//0=1st,1=2nd,etc
NSInteger SeaRow=[picker selectedRowInComponent:kSeaComponent];//0=fall,1=spring,2=summer
NSInteger CourseRow=[picker selectedRowInComponent:kCourseComponent];
NSString *num=Number[numRow];
NSString *season=Season[SeaRow];
NSString *course=Course[CourseRow];
NSString *key=[NSString stringWithFormat:#"%# %#",num,season];
NSMutableArray *courses=self.tableEntries[key];
if (courses == nil) {
courses=[NSMutableArray new];
self.tableEntries[key]=courses;
}
[courses addObject:course];
}
NSDictionarys are unordered, so you need to give some thought to how you want to order the data in your table. You could use an array to hold the keys as in your original code and then sort this array.

Adding Strings in NSMutableArray

I am in my IOS application in which i am getting ID from server which i am saving in string and then add strings in NSMutableArray.I am not getting perfect method by which i can add the strings in array and use the array outside the scope.
Here is my code Please help me out::
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
NSMutableArray *array=[[NSMutableArray alloc]init];
i=0;
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inResponseDictionary);
if (inRequest.sessionInfo == kUploadImageStep)
{
snapPictureDescriptionLabel.text = #"Setting properties...";
NSLog(#"%#", inResponseDictionary);
NSString* photoID =[[inResponseDictionary valueForKeyPath:#"photoid"] textContent];
flickrRequest.sessionInfo = kSetImagePropertiesStep;
// for uploading pics on flickr we call this method
[flickrRequest callAPIMethodWithPOST:#"flickr.photos.setMeta" arguments:[NSDictionary dictionaryWithObjectsAndKeys:photoID, #"photo_id", #"PicBackMan", #"title", #"Uploaded from my iPhone/iPod Touch", #"description", nil]];
[self.array addObject:photoID];
arr=array[0];
counterflicker++;
NSLog(#" Count : %lu", (unsigned long)[array count]);
}
How can i add the photoID(Strings) in the array?
Please help me out..
for adding NSString in NSMutableArray is like this
NSString *str = #"object";
NSMutableArray *loArr = [[NSMutableArray alloc] init];
[loArr addObject:str];
In your code Why are you using self.array ? just write like this. [array addObject:photoID];
self keyword is used for global variables but here in your code
"array" is a local variable .So need of self.array
[array addObject:photoID];
Before adding check that photoID is nil or not
if (photoID.length > 0) {
[array addObject:photoID];
}
I observe that in your code. you declare mutable array in local scope.
So just use
[array addObject:photoID];
Instead of
[self.array addObject:photoID];
May be you are create property for this array with same name, then you need to alloc it.
If you create a property for this then remove local declaration and alloc array like this.
self.array=[[NSMutableArray alloc]init];
and then use
[self.array addObject:photoID];

Resources