Memory Management Issue with CoreData - objective-c

Note: This question has been completely re-organized due to so many down votes.
I am displaying a UITableViewController using NSFetchedResults with core data.
It displays fine, but when I push a new view controller and the user uses the back button to navigate back to the UITableView its crashes with that error.
I have been battling this for weeks and have not figured out why. I can tell that its likely related to memory management but I cant find it anywhere.
Update: Using Instruments-Zombies I found out that in fact it was crashing on CoreData -prepareResultsForResultsSet. See image
Here is the code from my FetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController {
NSManagedObjectContext *thecontext;
thecontext = [(Logix_AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"TimeOff" inManagedObjectContext:thecontext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"timeOffStartDate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:thecontext sectionNameKeyPath: #"timeOffType" cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
fetchedResultsController.delegate = self;
[sort release];
[fetchRequest release];
[theFetchedResultsController release];
return fetchedResultsController;
}

Can you copy/paste the actual error from Xcode? And backtrace of where the crash happens, if any?
You definitely should not be autoreleaseing the object returned by +imageNamed:; that object is already autoreleased.
Your comment:
iVacationTimeApp[47892:19d03] -[CFString respondsToSelector:]: message sent to deallocated instance 0x95c9140
There is your answer. You have an overreleased object. May be the image, might be something else. Turn on Zombie detection in Instruments and run again.

Related

Mogenerator with NSFetchedResultsController - 0 sections

I am populating a UITableView from Core Data using an NSFetchedResultsController. The data is coming from an NSManagedObject subclass generated by Mogenerator called MenuItem. The MenuItem entity has a SectionID parameter that is an NSNumber and this is used to determine what section the item should be in within the table view.
I performed a test fetch on the data and confirmed that Core Data was populated correctly. All was fine.
The NSFetchedResultsController is created as follows and the sectionKeyNamePath is set to #"sectionId":
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MenuItem" inManagedObjectContext:self.persistenceController.moc];
[fetchRequest setEntity:entity];
fetchRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"sectionId" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:#"rowId" ascending:YES]];
NSFetchedResultsController *frc = nil;
frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.persistenceController.moc
sectionNameKeyPath:#"sectionId"
cacheName:nil];
The problem (and solution):
With this code, the sections are not identified. The NSFetchedResultsController always returns 0. This worked previously when I created the NSMO subclass manually, so I figured it was something related to Mogenerator.
If I change the sectionNameKeyPath to be #"primitiveSectionId" then it works.
Hopefully this will help somebody in the future, but I don't understand what is going on here. Please could somebody explain why this fixes the problem?
Thanks
Why are you setting the FRC to nil? Try this (it works for me using an NSNumber Attribute):
With mogenerator you can get the entity using "[MenuItem entityName]" and access attributes using MenuItemAttributes.sectionId, for example.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MenuItem entityName]];
fetchRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:MenuItemAttributes.sectionId ascending:YES], [NSSortDescriptor sortDescriptorWithKey:MenuItemAttributes.rowID ascending:YES]];
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.persistenceController.moc
sectionNameKeyPath:MenuItemAttributes.sectionId
cacheName:nil];
// Make sure you set your frc as the delegate
frc.delegate = self;
NSError *error = nil;
if (![fetcher performFetch:&error]) {
/*
* Did you execute the request?
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
NSLog(#"%lu", [frc.sections count]);

Xcode: table view cells only being created when I use a breakpoint. Why?

When I put a break point right on the line
"if (coordinator!= nil){"
the table view that is created from core data works correctly.
If I remove or put the breakpoint anywhere before that in my code it does not show the table view cells.
- (NSManagedObjectContext *) sharedManagedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
[_managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
}
return _managedObjectContext;
}
I have no clue as to how this is happening and had very little luck finding any other situations similar to this one.
Thank you for your help in advance!
Edit 1:
Here is the code that is being used to fetch the data from coredata
- (BOOL) setupFetchedResultsController:(NSError **) error {
self.managedObjectContext = [[PhotoBreezePersistentStoreManager shared] sharedManagedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"GeoTrack" inManagedObjectContext:self.managedObjectContext]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"trackName" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
controller.delegate = self;
self.fetchedResultsController = controller;
return [controller performFetch:error];
}
If I put a breakpoint in any of the above code...
after: "self.managedObjectContext = [[PhotoBreezePersistentStoreManager shared] sharedManagedObjectContext];"
... it will still work.
I'm pretty new to objective-c/cocoa so im not absolutely sure if a queue or thread is involved. I will however look into what you mentioned
Thanks!
Not enough information to really say; you would need to post details related to the creation/population of the table view.
However, this does sound like a classic race condition. Any threads or queues involved?

Objective C - NSManagedObjectContext and NSFetchedResultsController release handling

i need some information about memory management with NSManagedObjectContext objects.
I`m programming on an ipad-App and i work with core data objects.
My UIApplicationDelegate controls the NSManagedObjectContext:
- (NSManagedObjectContext *)managedObjectContext {
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
I`m using instances of the ManagedObjectContext to display my Core Data Objects.
like this.
example table view controller:
CRMAppDelegate *appDelegate = (CRMAppDelegate*) [[UIApplication sharedApplication] delegate];
self.managedObjectContext = appDelegate.managedObjectContext;
// Initialize NSFetchedResultsController to retrieve data from the database.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"Contact" inManagedObjectContext:self.managedObjectContext]];
// Sort results ascending by last name, first name.
NSSortDescriptor *sortDescriptorFirstLetterLastName = [[NSSortDescriptor alloc] initWithKey:#"firstLetterOfLastName" ascending:YES];
NSSortDescriptor *sortDescriptorLastName = [[NSSortDescriptor alloc] initWithKey:#"name_last" ascending:YES];
NSSortDescriptor *sortDescriptorFirstName = [[NSSortDescriptor alloc] initWithKey:#"name_first" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorFirstLetterLastName, sortDescriptorLastName, sortDescriptorFirstName, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptorFirstLetterLastName release];
[sortDescriptorFirstName release];
[sortDescriptorLastName release];
/*
if ([self.managedObjectContext countForFetchRequest:fetchRequest error:NULL] == 0) {
[self reloadContactData];
}
*/
// Create NSFetched Results controller instance.
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:#"firstLetterOfLastName"
cacheName:#"ContactsViewCache"];
[fetchRequest release];
self.fetchedResultsController.delegate = self;
// Load data.
NSError *error;
if (![fetchedResultsController performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
Is it ok to instance the NSManagedObjectContext like this? Because, the retainCount of the context is increasing til 10 while i`m testing my APP, even though i'm releasing the the context in "viewDidUnload" and "dealloc".
I`ve tried retain the context in a handler class like this:
- (NSManagedObjectContext *)getManagedObjectContext
{
NSManagedObjectContext *context = [self.managedObjectContext autorelease];
return context;
}
Whats the best way to interact with NSManagedObjectContext - objects and instances?
Thx and sry for my stuoid question :)
The value returned by retainCount is meaningless. Don't bother looking at it.
Use the Leaks instrument or heapshot analysis to determine if your app is leaking.

How to use ManagedObjectContext with threads

This is probably a very straight forward application, but I am new to Objective-C (coming from Java) and the whole memory management and "EXC_BAD_ACCESS" errors are breaking my heart.
I have a normal NavigationController iPhone App, with Core Data. in the AppDelegate the NSManagedObjectContext is created and passed to the RootViewController. A view things are looked up directly from the main thread to populate the table, and that seems to work fine.
The App is somekind of RSS-type reader, so as soon as the App starts I fire a thread to fetch new data and update the view:
-(void)updateData:(id)sender {
UIActivityIndicatorView *activityIndicator =
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[activityIndicator startAnimating];
UIBarButtonItem *activityItem =
[[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[activityIndicator release];
self.navigationItem.leftBarButtonItem = activityItem;
[activityItem release];
// Start thread to update the data
[NSThread detachNewThreadSelector:#selector(doUpdateData) toTarget:self withObject:nil];
}
-(void)doUpdateData{
NSLog(#"Update data Thread (in 5 sec.)");
[NSThread sleepForTimeInterval:5];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
DataManager *data = [[DataManager alloc] initWithContext:managedObjectContext];
[data updateData];
[data release];
data=nil;
[self performSelectorOnMainThread:#selector(finishUpdateData) withObject:nil waitUntilDone:NO];
[pool release];
}
-(void)finishUpdateData{
self.navigationItem.leftBarButtonItem = updateBttn;
DataManager *data = [[DataManager alloc] initWithContext:managedObjectContext];
objects = [data getArticles];
[data release];
data=nil;
NSLog(#"Amount of records after update: %d", [objects count]);
[self.tableView reloadData];
}
The problem is that this doesn't work. In the DataManager, first settings need to be retrieved, and as soon as the NSEntityDescription is created I get the "EXC_BAD_ACCESS":
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed.
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Setting" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"key" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchLimit:1];
.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
}
return fetchedResultsController;
}
I guess the pointer to the ManagedObjectContext is wrong, as a result from running in a different thread and memory-pool. So how do you create such an application if that is the issue), how do I get a reference to the original ManagedObjectContext format he thread?
[EDIT]
I also tried to use
iDomsAppDelegate *appDelegate = (iDomsAppDelegate *)[[UIApplication sharedApplication] delegate];
DataManager *data = [[DataManager alloc] initWithContext:appDelegate.managedObjectContext];
in doUpdateData (as hinted by other posts), but that gives the same result
Managed Object Contexts are not thread safe. Apple's guidelines indicate that you must have a separate instance of NSManagedObjectContext per thread.

NSFetchedResultsController always returns NSManagedObject objects instead of custom

I am using CoreData and have an Entity ContactList defined, which I created using the XCode xcdatamodel tool (or whatever you call that built-in thing:). I also set the Entity's Class name to "ContactList". I then used rentzsch's mogenerator (http://github.com/rentzsch/mogenerator) to generate my custom class files and added the simple method "toString" to my ContactList class.
The fetchedResultsController callback is pretty much standard and looks as follows:
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"ContactList" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return fetchedResultsController_;
}
Now, when I start my application and try to call that method on a "ContactList" object, which in turn I get from a NSFetchedResultsController, I get
ContactList *contactList = (ContactList *) [self.fetchedResultsController objectAtIndexPath:indexPath];
[contactList toString];
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject toString]: unrecognized selector sent to instance 0x6af7bf0'
As the message shows, somehow the NSFetchedResultsController does not return a "ContactList" object, but a more general NSManagedObject instead.
Does anybody know why and how to resolve this???
I had this same problem - Caused because I had previously renamed the Entity's Managed Object subclass. In the Data Modeler, make sure in the Inspector for the entity, both the "Name" and the "Class" are set correctly.
Ok, I figured this it out.
The problem was that the mogenerator script did not add its generated source files to the project's compile target. This way the classes never got compiled and included (I wonder how it worked without any model object classes :)
After adding the .xcdatamodel file to the Target (RightClick on .xcdatamodel file -> Targets -> check your project) everything works now.
For further info go here