Memory problems with NSMutableDictionary, causing NSCFDictionary memory leaks - cocoa

Help me please with the following problem:
- (NSDictionary *)getGamesList
{
NSMutableDictionary *gamesDictionary = [[NSMutableDictionary dictionary] retain];
// I was trying to change this on the commented code below, but did have no effect
// NSMutableDictionary *gamesDictionary = [[NSMutableDictionary alloc] init];
// [gamesDictionary retain];
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSArray *gameDate = [key componentsSeparatedByString:#" "];
NSNumber *_id = [[NSNumber alloc] initWithInt:sqlite3_column_int(statement, 0)];
NSString *date_time = [NSString stringWithFormat:#"%#, %#",[gameDate objectAtIndex:0],[gameDate objectAtIndex:2]];
if (![gamesDictionary valueForKey:date_time]) [gamesDictionary setValue:[NSMutableArray array] forKey:date_time];
[[gamesDictionary valueForKey:date_time] addObject:[[_id copy] autorelease]];
[_id release];
}
sqlite3_reset(statement);
return gamesDictionary;
}
The leak starts in another method of another class, there the getGamesList method is called, like this:
NSMutableDictionary *gamesDictionary;
gamesDictionary = [[NSMutableDictionary dictionaryWithDictionary:[appDelegate getGamesList]] retain];
After that there are a lot of leaks that points to NSCFArray in the string:
NSArray *keys = [[NSArray arrayWithArray:[gamesDictionary allKeys]] retain];
in this method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *keys = [[NSArray arrayWithArray:[gamesDictionary allKeys]] retain];
if ([keys count] != 0) return [[keys objectAtIndex:section] uppercaseString];
return #"";
}
I assume these things are connected to each other, but I still can not understand all of the memory management tips.
Thanks a lot!

Didn't use Cocoa for years (that's why I can't tell you an exact answer :/). But I guess your problem is that you systematically use retain on your objects.
Since the object reference count never get to 0, all dictionaries are keep in memory and not freed.
Try to remove the retain on [NSArray arrayWithArray] and [NSMutableDictionary dictionaryWithDictionary
http://en.wikibooks.org/wiki/Programming_Mac_OS_X_with_Cocoa_for_beginners/Some_Cocoa_essential_principles#Retain_and_Release

It does look like you are over-retaining your array.
When you create the gamesDictionary it is created with an retain count of +1. You then retain it (count becomes +2). When you get the value outside this function you retain again (count becomes +3).
You are correct that if you create an object you are responsible for it's memory management. Also, when you get an object from a method, you should retain it if you want to keep it around for longer than the span of the function. In your case, you just want to get at some of the properties of the object, so you don't need to retain it.
Here is a suggestion:
- (NSDictionary *)getGamesList
{
NSMutableDictionary *gamesDictionary = [NSMutableDictionary dictionary]; // Remove the retain.
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSArray *gameDate = [key componentsSeparatedByString:#" "];
NSNumber *_id = [[NSNumber alloc] initWithInt:sqlite3_column_int(statement, 0)];
NSString *date_time = [NSString stringWithFormat:#"%#, %#",[gameDate objectAtIndex:0],[gameDate objectAtIndex:2]];
if (![gamesDictionary valueForKey:date_time]) [gamesDictionary setValue:[NSMutableArray array] forKey:date_time];
[[gamesDictionary valueForKey:date_time] addObject:[[_id copy] autorelease]];
[_id release];
}
sqlite3_reset(statement);
return gamesDictionary;
}
This next bit is messy. you create a new dictionary and retain it. The original dictionary is not autoreleased, so the count isn't decremented and it always hangs around. Just assign the dictionary rather than create a new one.
NSMutableDictionary *gamesDictionary = [[appDelegate getGamesList] retain];
// Retaining it, becuase it looks like it's used elsewhere.
Now, in this method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *returnString;
// Don't need to retain the keys because you are only using it within the function
// and since you didn't alloc, copy or retain the array it contains, you aren't responsible for it's memory management.
NSArray *keys = [NSArray arrayWithArray:[gamesDictionary allKeys]];
if ([keys count] != 0) {
returnString = [[NSString alloc] initWithString:[[keys objectAtIndex:section] uppercaseString]];
return [returnString autorelease];
}
return #"";
}

Related

When sorting a NSMutable array from core data, i get an error

Below is my viewDidLoad method in a tableViewController. When viewDidLoad runs this error comes up
2014-03-03 12:44:54.904 SalesCRM2[30188:70b] -[_PFArray sortUsingDescriptors:]: unrecognized selector sent to instance 0x8c45710
2014-03-03 12:44:54.931 SalesCRM2[30188:70b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_PFArray sortUsingDescriptors:]: unrecognized selector sent to instance 0x8c45710'
on this line of code
[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];
Here is the whole method
- (void)viewDidLoad
{
[super viewDidLoad];
JCAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Customers"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
NSArray *objects = [context executeFetchRequest:request
error:&error];
NSMutableArray *array = (NSMutableArray *)objects;
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"firstName" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];
if ([objects count] == 0)
{
//_isEmpty = YES;
}
else
{
//_isEmpty = NO;
_resultsArray = (NSMutableArray *)objects;
NSLog(#"resultsArray: %i",[_resultsArray count]);
// matches = objects[0];
// _address.text = [matches valueForKey:#"address"];
// _phone.text = [matches valueForKey:#"phone"];
// _status.text = [NSString stringWithFormat:
// #"%lu matches found", (unsigned long)[objects count]];
}
}
Read the error message. It's telling you the problem. You can say sortUsingDescriptors: to an immutable array. It is immutable.
Now, as for what you are doing wrong, it is much more interesting! You are saying:
NSMutableArray *array = (NSMutableArray *)objects;
Perhaps you believe that this turns an immutable array into a mutable array. It doesn't. You can't turn a silk purse into a sow's ear by typecasting. You may lie to the compiler (and you did, by typecasting to a false class), but you can't lie to the runtime. What an object is, that's what it is, no matter what you call it.
If you want a mutable array, you must make a mutable array (e.g. by calling mutableCopy) - it isn't enough to say a thing is a mutable array when in fact it isn't.

NSMutableArray have error empty array

i have some problem with NSMutablearray and JSON parse.
So what i doing? A make parse from JSON and send to my TableViewCell.
I have my code:
h:
{
NSMutableData *webdata;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableArray *array2;
NSTimer *timer;
}
m:
{
[super ViewDidload]
[[self tableTrack] setDelegate:self];
[[self tableTrack] setDataSource:self];
array = [[NSMutableArray alloc] init];
array2 = [[NSMutableArray alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(plistGet) userInfo:nil repeats:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error load");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:#"playlist"];
for (NSDictionary *diction in playlist) {
NSDictionary *artist = [diction objectForKey:#"artist"];
NSDictionary *song = [diction objectForKey:#"song"];
NSString *name = [artist objectForKey:#"name"];
NSString *namesong = [song objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
-(void)plistGet {
[array removeAllObjects];
[array2 removeAllObjects];
NSURL *url = [NSURL URLWithString:#"http://plist.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webdata = [[NSMutableData alloc]init];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
// return [array2 count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(! cell)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
}
cell.textLabel.text = [array2 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [array objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(50/255.0) green:(200/255.0) blue:(255/255.0) alpha:1];
[tableTrack setBackgroundView:nil];
tableTrack.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.font=[UIFont fontWithName: #"Helvetica" size:11];
UIFont *myFont = [ UIFont fontWithName: #"Arial" size: 9.0 ];
cell.textLabel.font = myFont;
self.tableTrack.separatorStyle = UITableViewCellSeparatorStyleNone;
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor darkGrayColor].CGColor;
separatorView.layer.borderWidth = 0.5;
[cell.contentView addSubview:separatorView];
return cell;
}
All work very good but after 5 or 3 minutes i have error and my app crashed.
Error:
2013-06-21 12:32:41.502 EuropaPlusUA[651:707] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
* First throw call stack:
(0x353f188f 0x37798259 0x3533a9db 0xfa9d5 0x32e85efb 0x32e84fd9 0x32e84763 0x32e28f37 0x353501fb 0x32220aa5 0x322206bd 0x32224843 0x3222457f 0x3221c4b9 0x353c5b1b 0x353c3d57 0x353c40b1 0x353474a5 0x3534736d 0x36fe3439 0x32e53cd5 0xf8843 0xf87d0)
terminate called throwing an exception
What is it? Help please.
Your problem is that you probably do another plistget method after that 3-5 minutes. That method will throw away all objects from your array. During the time your data is getting loaded and the time you cleared your array, the table datasource is empty, however you are trying to get this object from index 0. This is why your crash happens.
The solution however is simple. Do not call the removeAllObjects method at all.
Simply replace the array with the contents that you will retrieve.
Replace mechanic that you will need to do the moment you get the data from your server:
NSMutableArray *tempDataArray = [[NSMutableArray alloc] init];
//put retrieved data from your web call in the tempDataArray
array = tempDataArray;
me thinks the only objectAtIndex is here.
cell.detailTextLabel.text = [array objectAtIndex:indexPath.row];
seems likely array was emptied by plistget
[array removeAllObjects];
Totumus Maximus is right.
If you just need to bridge the gap between getting clearing the arrays and reloading the data why not try NOT deleting them until the new data is ready? Then just replace them
Alternatively make a copy of them first (say to backUpArray and backUpArray2) and then check to see if you have data in array/array2 (something like if([array count]) or if (array) {...) before you try and load the cell.
If you have nothing in the arrays use [backUpArray lastObject] to give you some data for the (brief ?) time until the arrays are reloaded.

Xcode: Remove objects from NSMutableArray based on NSDictionary

I am new to tableViews and dictionaries and i have a problem!
In ViewDidLoad i am initializing many MutableArrays and i am adding data using NSDictionary. Example:
- (void)viewDidLoad {
nomosXiou=[[NSMutableArray alloc] init];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:#"Mary",#"name",#"USA",#"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:#"Peter",#"name",#"Germany",#"country", nil]];
[super viewDidLoad];
// Do any additional setup after loading the view.}
In a previous ViewController the user selects a Country. Based on that selection, how could i remove from my arrays all the other entries???
Thanks in advance...
First note that your code fragment has an error. It should read:
NSMutableArray *nomosXiou= [[NSMutableArray alloc] init];
There are a number of ways to do what you want, but the most straightforward is probably the following:
NSString *countryName; // You picked this in another view controller
NSMutableArray *newNomosXiou= [[NSMutableArray alloc] init];
for (NSDictionary *entry in nomosXiou) {
if ([[entry objectForKey:#"country"] isEqualToString:countryName])
[newNomosXiou addObject:entry];
}
When this is done newNomosXiou will contain only the entries in nomosXiou that are from the country set in countryName.
Something like this will do the job:
NSMutableArray *nomosXiou = [[NSMutableArray alloc] init];
NSString *country = #"Germany"; // This is what you got from previous controller
// Some test data. Here we will eventually keep only countries == Germany
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:#"Mary",#"name",#"USA",#"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:#"Peter",#"name",#"Germany",#"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:#"George",#"name",#"Germany",#"country", nil]];
// Here we'll keep track of all the objects passing our test
// i.e. they are not equal to our 'country' string
NSIndexSet *indexset = [nomosXiou indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
return (BOOL)![[obj valueForKey:#"country"] isEqualToString:country];
}];
// Finally we remove the objects from our array
[nomosXiou removeObjectsAtIndexes:indexset];

xcode global nsmutablearray that keeps values

Did a search but cant seem to find exactly what I'm looking for
Basically I load values into a nsmutablearray in one method and then I want to access these values in another method to print them to a table
I declared the array in the app.h
NSMutableArray *clients;
Then in the app.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray *results = [responseString JSONValue];
clients = [[NSMutableArray alloc]init];
// Loop through each entry and add clients to array
for (NSDictionary *entry in results)
{
if (![clients containsObject:[entry objectForKey:#"client"]])
{
[clients addObject:[entry objectForKey:#"client"]];
}
}
}
Now Im try to acces the clients array in another method
I have seen some suggestions to use extern in the app.h? Some sort of global variable?
Any help would be appreciated
Thanks
Take the clients array in app delegate class.declare the property,synthesizes in the app delegate class.Then in the below method write like this.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
YourApplicationDelegate *delegate = [UIApplication sharedApplication]delegate];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray *results = [responseString JSONValue];
clients = [[NSMutableArray alloc]init];
// Loop through each entry and add clients to array
for (NSDictionary *entry in results)
{
if (![clients containsObject:[entry objectForKey:#"client"]])
{
[delegate.clients addObject:[entry objectForKey:#"client"]];
}
}
}
after that suppose you if you want to use the clients array in another class do like this.
YourApplicationDelegate *delegate = [UIApplication sharedApplication]delegate];
NSLog(#"client array is %#",delegate.clients);

Cocoa Core Data: Setting default entity property values?

I know I can set default values either in the datamodel, or in the -awakeFromInsert method of the entity class. For example, to make a "date" property default to the current date:
- (void) awakeFromInsert
{
NSDate *now = [NSDate date];
self.date = now;
}
How though can I make an "idNumber" property default to one greater than the previous object's idNumber?
Thanks, Oli
EDIT: Relevant code for my attempt (now corrected)
- (void) awakeFromInsert
{
self.idNumber = [NSNumber numberWithInt:[self maxIdNumber] + 1];
}
-(int)maxIdNumber{
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Flight" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
// Set example predicate and sort orderings...
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"idNumber > %#", [NSNumber numberWithInt:0]];
[request setPredicate:predicate];
[request setFetchLimit:1];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"idNumber" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil | array.count == 0)
{
return 0;
}
return [[[array objectAtIndex:0] valueForKey:#"idNumber"] intValue];
}
If the maxIdNumber method is called, the new object is added to the table twice!? (but with the correct idNumber). The two entries in the table are linked - editing / removing one also edits / removes the other. For this reason I believe it has something to do with the managed object context. For what its worth, the outcome (two copies) is the same no matter how many times the maxIdNumber method is called in the awakFromNib; even if self.idNumber is just set to [NSNumber numberWithInt:5] and the maxIdNumber method is just called for a throwaway variable.
Any clues??
SOLVED IT!
Ok, the problem of double entry occurs when a fetch request is performed from within the awakeFromInsert method. Quoting from the docs:
You are typically discouraged from performing fetches within an implementation of awakeFromInsert. Although it is allowed, execution of the fetch request can trigger the sending of internal Core Data notifications which may have unwanted side-effects. For example, on Mac OS X, an instance of NSArrayController may end up inserting a new object into its content array twice.
A way to get around it is to use the perfromSelector:withObject:afterDelay method as outlined here (I am only allowed to post one hyperlink :( ):http://www.cocoabuilder.com/archive/cocoa/232606-auto-incrementing-integer-attribute-in-awakefrominsert.html.
My working code is now as follows: (note, I have put the bulk of the fetching code used above into a category to tidy it up a little, this allows me to use the method fetchObjectsForEntityName:withPredicate:withFetchLimit:withSortDescriptors:)
- (void) awakeFromInsert
{
[self performSelector:#selector(setIdNumber) withObject:nil afterDelay:0];
self.date = [NSDate date];
}
-(void)setIdNumber
{
int num = 0;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"idNumber" ascending:NO];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"idNumber > %#", [NSNumber numberWithInt:0]];
NSArray *array = [[self managedObjectContext] fetchObjectsForEntityName:#"Flight"
withPredicate:predicate
withFetchLimit:0
withSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
if (array != nil & array.count != 0)
{
num = [[[array objectAtIndex:0] valueForKey:#"idNumber"] intValue];
}
num ++;
[self setIdNumber:[NSNumber numberWithInt:num]];
}
Let me know what you think!
One Approach: Create a fetch request of all instances of your entity with a limit of 1, sorted by idNumber to get the highest number.
Another Approach: Keep the highest idNumber in your store's metadata and keep incrementing it.
There are plenty of arguments for and against either. Ultimately, those are the two most common and the choice is yours.
An easier way to do that is to override the newObject method of NSArrayController:
- (id) newObject
{
id result=[super newObject];
[result setValue: [NSDate date] forKey: #"date"];
return result;
}

Resources