I am getting this error message in the console:
*** _NSAutoreleaseNoPool(): Object 0x10d2e0 of class NSPathStore2
autoreleased with no pool in place - just leaking
I can't figure out what is the error?
Thanks.
This is a classic memory management issue, you are autoreleasing some objects without having an autorelease pool in place. Autoreleasing is not a magic. There is an object of type NSAutoreleasePool that keeps track of all objects you autorelease and ‘from time to time’ releases them:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// An autoreleased object referenced by our pool.
id object = [NSNumber numberWithInt:1];
[pool drain];
// Our object no longer valid.
Each thread has to have its own autorelease pool. That’s quite logical, because threads run ‘at the same time’ and if they shared a common autoreleased pool, it could release an object while you are still working with it.
Now the point. There is a default autorelease pool in the main thread of every application, which means you don’t have to think about all of this and autoreleased objects are collected just fine. But if you create another thread, you are usually forced to also create an autorelease pool for this thread. Otherwise there is nobody to claim the autoreleased objects and they just leak. Which is exactly why you are getting the warning.
Leaking thread without an autorelease pool can look like this:
- (void) doSomethingInBackground
{
id object = [NSNumber numberWithInt:1];
}
- (void) someOtherMethod
{
[self performSelectorInBackground:#selector(doSomethingInBackground);
}
The fix is simple:
- (void) doSomethingInBackground
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id object = [NSNumber numberWithInt:1];
[pool drain];
}
Now you only have to figure out where you are running code in another thread.
It sounds like you've spawned a method onto a new thread (possibly using + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument;)
Any method that runs on its own thread will need to have an autorelease pool setup up to catch any autoreleased objects:
- (void)myLovelyThreadedMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
... // your code here
[pool release];
}
Try using the Clang Static Analyzer
Related
I have an NSCollectionView specified as both my DataSource and my Delegate.
I have two issues:
Rather than doing the registerClass method, attempting to instead use the 3 lines of commented code with the (non-nil) protoNib means of registering with an NSCollectionView causes theItem to always be nil.
Using the class registry option, all works mostly fine. But if I remove the willDisplayItem and didEndDisplayingItem stubs, the system eats up gobs of memory on its first call to itemForRepresentedObjectAtIndexPath (with thousands of internal calls to these two stubs) and eventually crashes. Instruments shows thousands of 4k #autoreleasepool content items being created by AppKit.
Any idea why this might be happening?
-(void)awakeFromNib {
[self registerClass:[MECollectionViewItem class] forItemWithIdentifier:#"EntityItem"];
// NSString *nibName = NSStringFromClass([MECollectionViewItem class]);
// NSNib *protoNib = [[NSNib alloc] initWithNibNamed:nibName bundle:nil];
// [self registerNib:protoNib forItemWithIdentifier:#"EntityItem"];
__weak typeof(self) weakSelf = self;
[self setDelegate:weakSelf];
[self setDataSource:weakSelf];
...
}
- (MECollectionViewItem *)collectionView:(NSCollectionView *)collectionView
itemForRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath;
{
MECollectionViewItem *theItem = [self makeItemWithIdentifier:#"EntityItem"
forIndexPath:indexPath];
return theItem;
}
-(void)collectionView:(NSCollectionView *)collectionView
willDisplayItem:(NSCollectionViewItem *)item
forRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath
{
}
-(void)collectionView:(NSCollectionView *)collectionView
didEndDisplayingItem:(nonnull NSCollectionViewItem *)item
forRepresentedObjectAtIndexPath:(nonnull NSIndexPath *)indexPath
{
}
The Appkit classes are not designed to be their own delegate. NSCollectionView implements several NSCollectionViewDelegate methods and calls the delegate. I don't know why it's implemented like this and it doesn't feel right but it is what it is. If the collection view is its own delegate and a delegate method isn't implemented in the subclass then the call causes an infinite loop. Solution: don't set delegate to self.
I have a mainContext that is used on the main thread. When the mainContext is created, I add an observer to the NotificationCenter for NSManagedObjectContextDidSaveNotification notifications.
If a new thread gets created and needs an NSManagedObjectContext, I create the context on the new thread and store some info for it. I save changes to the context on the new thread.
My notification handler gets called and merges changes for all contexts on their threads. I have a merge policy for each context in affect and I am merging changes on the appropriate threads.
I still randomly get "optimistic locking failure". Is there something I am missing?
- (void)contextChanged:(NSNotification *)notif
{
//gets called from the thread(where the context was) that made the changes
//iterate over all contexts and mergeChanges on their thread
NSLog(#"NotifContext %# %p", [notif object], [NSThread currentThread]);
//always check the main
if([notif object] != [self mainContext]){
NSLog(#"merge with main %#", [self mainContext]);
[[self mainContext] performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:) withObject:notif waitUntilDone:NO];
}
//check alternate cotexts and merge changes on their threads
NSDictionary *altContexts = [self.altContexts copy];
for(NSString *threadAddress in altContexts){
NSDictionary *info = [altContexts objectForKey:threadAddress];
NSManagedObjectContext *context = [info objectForKey:#"context"];
if(context != NULL && [notif object] != context){
NSLog(#"merge with %#", context);
NSThread *thread = [info objectForKey:#"thread"];
[context performSelector:#selector(mergeChangesFromContextDidSaveNotification:) onThread:thread withObject:notif waitUntilDone:NO];
}else{
NSLog(#"not with %#", context);
}
}
[altContexts release];
}
waitUntilDone:NO //should have been YES
I overlooked this. I meant to wait until it was done. Otherwise, the save happens (on thread 2), the notification gets dispatched, the contextChanged: handler gets triggered, the other contexts are told to merge changes on their thread (say thread 1), and thread 2 continues before the context on thread 1 actually gets to save.
I'm attempting to perform a fairly large CoreData import (around 25,000 rows) while still maintaining a fairly low memory footprint. I've read the documentation surrounding efficient importing of data and have endeavoured to implement everything suggested there (including setting things like my MOC's undoManager to nil).
Unfortunately, my applications memory usage still climbs to around 180MB when running the below code. Upon completion the application will sit at around the 180MB mark, regardless of the final NSAutoreleasePool drain call.
Running the application through Allocations shows that 95% of the memory usage is attributable to my [self.moc save:&error] call. What am I doing wrong here?
- (void)generateCache
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUInteger count = 0, batchSize = 1000;
// SNIP SNIP
// Iterate over our directory structure
for(NSString *item in directoryStructure)
{
NSDictionary *info = [fm attributesOfItemAtPath:item error:nil];
FileRecord *record = (FileRecord *)[NSEntityDescription insertNewObjectForEntityForName:#"FileRecord" inManagedObjectContext:self.moc];
record.size = [NSNumber numberWithUnsignedLongLong:[info fileSize]];
record.path = item;
count ++;
if(count == batchSize)
{
NSError *error = nil;
if([self.moc save:&error])
{
NSLog(#"MOC saved down and reset");
[self.moc reset];
[pool drain];
pool = [[NSAutoreleasePool alloc] init];
count = 0;
}
}
}
// Perform any necessary last minute MOC saves
if (count != 0) {
[self.moc save:nil];
[self.moc reset];
}
// Drain our NSAutoreleasePool
[pool drain];
// Tell our main thread that we're done
if ([self respondsToSelector:#selector(completedCache)])
{
[self performSelectorOnMainThread:#selector(completedCache) withObject:nil waitUntilDone:NO];
}
}
Instead of dealing with auto-release pools, why not explicitly manage the life-cycle of your managed objects by creating them with NSManagedObject's initWithEntity:insertIntoManagedObjectContext:? You can safely release them after modifying the object's properties since a managed object context retains a newly inserted object -- till its saved to the persistent store.
Also, I should mention a couple of problems that I see with your code:
As someone mentioned above, you are not logging errors from the save: operation. You really should -- that may highlight some (possibly unrelated) problem.
If save: is successful, you really should not need to call reset. See this section in the core data guide.
Background
Cocoa app using core data Two
processes - daemon and a main UI
Daemon constantly writing to a data store
UI process reads from same data
store
Columns in NSOutlineView in UI bound to
an NSTreeController
NSTreeControllers managedObjectContext is bound to
Application with key path of
delegate.interpretedMOC
NSTreeControllers entity is set to TrainingGroup (NSManagedObject subclass is called JGTrainingGroup)
What I want
When the UI is activated, the outline view should update with the latest data inserted by the daemon.
The Problem
Main Thread Approach
I fetch all the entities I'm interested in, then iterate over them, doing refreshObject:mergeChanges:YES. This works OK - the items get refreshed correctly. However, this is all running on the main thread, so the UI locks up for 10-20 seconds whilst it refreshes. Fine, so let's move these refreshes to NSOperations that run in the background instead.
NSOperation Multithreaded Approach
As soon as I move the refreshObject:mergeChanges: call into an NSOperation, the refresh no longer works. When I add logging messages, it's clear that the new objects are loaded in by the NSOperation subclass and refreshed. It seems that no matter what I do, the NSOutlineView won't refresh.
What I've tried
I've messed around with this for 2 days solid and tried everything I can think of.
Passing objectIDs to the NSOperation to refresh instead of an entity name.
Resetting the interpretedMOC at various points - after the data refresh and before the outline view reload.
I'd subclassed NSOutlineView. I discarded my subclass and set the view back to being an instance of NSOutlineView, just in case there was any funny goings on here.
Added a rearrangeObjects call to the NSTreeController before reloading the NSOutlineView data.
Made sure I had set the staleness interval to 0 on all managed object contexts I was using.
I've got a feeling this problem is somehow related to caching core data objects in memory. But I've totally exhausted all my ideas on how I get this to work.
I'd be eternally grateful to anyone who can shed any light as to why this might not be working.
Code
Main Thread Approach
// In App Delegate
-(void)applicationDidBecomeActive:(NSNotification *)notification {
// Delay to allow time for the daemon to save
[self performSelector:#selector(refreshTrainingEntriesAndGroups) withObject:nil afterDelay:3];
}
-(void)refreshTrainingEntriesAndGroups {
NSSet *allTrainingGroups = [[[NSApp delegate] interpretedMOC] fetchAllObjectsForEntityName:kTrainingGroup];
for(JGTrainingGroup *thisTrainingGroup in allTrainingGroups)
[interpretedMOC refreshObject:thisTrainingGroup mergeChanges:YES];
NSError *saveError = nil;
[interpretedMOC save:&saveError];
[windowController performSelectorOnMainThread:#selector(refreshTrainingView) withObject:nil waitUntilDone:YES];
}
// In window controller class
-(void)refreshTrainingView {
[trainingViewTreeController rearrangeObjects]; // Didn't really expect this to have any effect. And it didn't.
[trainingView reloadData];
}
NSOperation Multithreaded Approach
// In App Delegate (just the changed method)
-(void)refreshTrainingEntriesAndGroups {
JGRefreshEntityOperation *trainingGroupRefresh = [[JGRefreshEntityOperation alloc] initWithEntityName:kTrainingGroup];
NSOperationQueue *refreshQueue = [[NSOperationQueue alloc] init];
[refreshQueue setMaxConcurrentOperationCount:1];
[refreshQueue addOperation:trainingGroupRefresh];
while ([[refreshQueue operations] count] > 0) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
// At this point if we do a fetch of all training groups, it's got the new objects included. But they don't show up in the outline view.
[windowController performSelectorOnMainThread:#selector(refreshTrainingView) withObject:nil waitUntilDone:YES];
}
// JGRefreshEntityOperation.m
#implementation JGRefreshEntityOperation
#synthesize started;
#synthesize executing;
#synthesize paused;
#synthesize finished;
-(void)main {
[self startOperation];
NSSet *allEntities = [imoc fetchAllObjectsForEntityName:entityName];
for(id thisEntity in allEntities)
[imoc refreshObject:thisEntity mergeChanges:YES];
[self finishOperation];
}
-(void)startOperation {
[self willChangeValueForKey:#"isExecuting"];
[self willChangeValueForKey:#"isStarted"];
[self setStarted:YES];
[self setExecuting:YES];
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isStarted"];
imoc = [[NSManagedObjectContext alloc] init];
[imoc setStalenessInterval:0];
[imoc setUndoManager:nil];
[imoc setPersistentStoreCoordinator:[[NSApp delegate] interpretedPSC]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:imoc];
}
-(void)finishOperation {
saveError = nil;
[imoc save:&saveError];
if (saveError) {
NSLog(#"Error saving. %#", saveError);
}
imoc = nil;
[self willChangeValueForKey:#"isExecuting"];
[self willChangeValueForKey:#"isFinished"];
[self setExecuting:NO];
[self setFinished:YES];
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
-(void)mergeChanges:(NSNotification *)notification {
NSManagedObjectContext *mainContext = [[NSApp delegate] interpretedMOC];
[mainContext performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}
-(id)initWithEntityName:(NSString *)entityName_ {
[super init];
[self setStarted:false];
[self setExecuting:false];
[self setPaused:false];
[self setFinished:false];
[NSThread setThreadPriority:0.0];
entityName = entityName_;
return self;
}
#end
// JGRefreshEntityOperation.h
#interface JGRefreshEntityOperation : NSOperation {
NSString *entityName;
NSManagedObjectContext *imoc;
NSError *saveError;
BOOL started;
BOOL executing;
BOOL paused;
BOOL finished;
}
#property(readwrite, getter=isStarted) BOOL started;
#property(readwrite, getter=isPaused) BOOL paused;
#property(readwrite, getter=isExecuting) BOOL executing;
#property(readwrite, getter=isFinished) BOOL finished;
-(void)startOperation;
-(void)finishOperation;
-(id)initWithEntityName:(NSString *)entityName_;
-(void)mergeChanges:(NSNotification *)notification;
#end
UPDATE 1
I just found this question. I can't understand how I missed it before I posted mine, but the summary is: Core Data wasn't designed to do what I'm doing. Only one process should be using a data store.
NSManagedObjectContext and NSArrayController reset/refresh problem
However, in a different area of my application I have two processes sharing a data store with one having read only access and this seemed to work fine. Plus none of the answers to my last question on this topic mentioned that this wasn't supported in Core Data.
I'm going to re-architect my app so that only one process writes to the data store at any one time. I'm still skeptical that this will solve my problem though. It looks to me more like an NSOutlineView refreshing problem - the objects are created in the context, it's just the outline view doesn't pick them up.
I ended up re-architecting my app. I'm only importing items from one process or the other at once. And it works perfectly. Hurrah!
I have an method which save files to the internet, it works but just slow. Then I'd like to make the user interface more smooth, so I create an NSThread to handle the slow task.
I am seeing a list of errors like:
_NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking
Without NSThread, I call the method like:
[self save:self.savedImg];
And I used the following to use NSThread to call the method:
NSThread* thread1 = [[NSThread alloc] initWithTarget:self
selector:#selector(save:)
object:self.savedImg];
[thread1 start];
Thanks.
Well first of all, you are both creating a new thread for your saving code and then using NSUrlConnection asynchronously. NSUrlConnection in its own implementation would also spin-off another thread and call you back on your newly created thread, which mostly is not something you are trying to do. I assume you are just trying to make sure that your UI does not block while you are saving...
NSUrlConnection also has synchronous version which will block on your thread and it would be better to use that if you want to launch your own thread for doing things. The signature is
+ sendSynchronousRequest:returningResponse:error:
Then when you get the response back, you can call back into your UI thread. Something like below should work:
- (void) beginSaving {
// This is your UI thread. Call this API from your UI.
// Below spins of another thread for the selector "save"
[NSThread detachNewThreadSelector:#selector(save:) toTarget:self withObject:nil];
}
- (void) save {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ... calculate your post request...
// Initialize your NSUrlResponse and NSError
NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error];
// Above statement blocks until you get the response, but you are in another thread so you
// are not blocking UI.
// I am assuming you have a delegate with selector saveCommitted to be called back on the
// UI thread.
if ( [delegate_ respondsToSelector:#selector(saveCommitted)] ) {
// Make sure you are calling back your UI on the UI thread as below:
[delegate_ performSelectorOnMainThread:#selector(saveCommitted) withObject:nil waitUntilDone:NO];
}
[pool release];
}
You need to mainly create an autorelease pool for the thread. Try changing your save method to be like this:
- (void) save:(id)arg {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//Existing code
[pool drain];
}
You will not you that the above does not call release on the NSAutoreleasePool. This is a special case. For NSAutoreleasePool drain is equivalent to release when running without GC, and converts to a hint to collector that it might be good point to run a collection.
You may need to create a run loop. I will add to Louis's solution:
BOOL done = NO;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSRunLoop currentRunLoop];
// Start the HTTP connection here. When it's completed,
// you could stop the run loop and then the thread will end.
do {
SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished)) {
done = YES;
}
} while (!done);
[pool release];
Within the thread, you need to create a new autorelease pool before you do anything else, otherwise the network operations will have issues as you saw.
I don't see any reason for you to use threads for this. Simply doing it asynchronously on the run loop should work without blocking the UI.
Trust in the run loop. It's always easier than threading, and is designed to provide the same result (a never-blocked UI).