Fix random mergeChangesFromContextDidSaveNotification: crashes

Getting crashes when merging NSManagedObjectContexts?

1. Clean up leaked observers. We were getting a really random crash trying to merge contexts between threads. Turns out we forgot to clean up an observer on one of our views that was using a NSManagedObject being merged. When the object changed, the observer fired on a deallocated view. Enables zombies to find the culprit.

2. Merge on the proper thread. If you must use multiple contexts, the recommended configuration is one context per-thread. When interacting with a context, you must make sure to do so on the proper thread. Block example:

    - (void)contextDidSaveNotification:(NSNotification*)saveNotification {
        [self.mergeContext performBlock:^{
            [self.mergeContext mergeChangesFromContextDidSaveNotification:notification];
        }];
     }

3. Fault in updated objects. This is a last resort type of thing but it’s possible the object for some reason doesn’t exist in the context we’re merging to yet (even though it should). I found that faulting in updated objects before merging fixed this issue before. http://www.mlsite.net/blog/?p=518

4. Avoid manipulating an object across contexts simultaneously. I’ve seen it cause crashes (awakeFromSnapshotEvents: message sent to deallocated instance), especially when using nested contexts.

Advertisements

The case of NSCursor being mysteriously reset on the initial drag

Cursor being mysteriously reset on the first drag? It’s somehow caused by having a NSToolbar on your window.

Sample project available here: https://github.com/panupan/TestDrag

After some investigating with a NSCursor category:

@implementation NSCursor(Hack)
- (void)set
{
    NSLog(@"%@",[NSThread callStackSymbols]);
}
@end

I found this fixed it (use at your own risk!):

@interface NSDragDestination : NSObject {
    unsigned long long _lastDragDestinationOperation;
}
@end
@implementation NSDragDestination(NSToolbarFix)
- (void)_setLastDragDestinationOperation:(unsigned long long)arg1;
{
    // Fixes NSToolbar breaking default NSCursor behavior, e.g., cursor image on initial drag.
    _lastDragDestinationOperation = arg1;
}
@end

How to store Blocks in NSDictionary

Are you getting a crash trying to store your block in a NSDictionary instance?

From http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html:

Blocks “just work” when you pass blocks up the stack in ARC mode, such as in a return. You don’t have to call Block Copy any more. You still need to use [^{} copy] when passing “down” the stack into arrayWithObjects: and other methods that do a retain.

From http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html:

As an optimization, block storage starts out on the stack—just like blocks themselves do. If the block is copied using Block_copy (or in Objective-C when the block is sent a copy), variables are copied to the heap. Thus, the address of a __block variable can change over time.

This means that the block variables in your function are stored in the stack, and when the function returns, they get wiped out. If you’re using ARC, your crash is caused by block variables being over released. Calling copy on a block makes block variables stick around.

Here’s what it looks like:

        __weak id weakSelf = self;  // Weak block variable prevents retain cycle.
        void (^myBlock)() = ^() { 
            NSLog(@"Called from %@!", weakSelf);
        };
        
        // Copy the block so the block variable sticks around!
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[myBlock copy], @"MyBlock", nil];    

How to observe a collection of objects and changes to their properties

The easy way is to use an NSArrayController and add an observer like so:

[friendsArrayController addObserver:self forKeyPath:@"arrangedObjects.name" options:0 context:nil];

The hard way is to observe a model’s collection property and add/remove observers when objects get added/removed from the collection like so:

[person addObserver:self forKeyPath:@"friends" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == person && [keyPath isEqualTo:@"friends"]) {
            if ([[change valueForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeInsertion) {
                for (Friend *newFriend in [change valueForKey:NSKeyValueChangeNewKey]) {
                    if (![observedFriends containsObject:newFriend]) {
                        [newFriend addObserver:self forKeyPath:@"name" options:0 context:nil];
                    }
                }
            }
            else if ([[change valueForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeRemoval) {
                for (Friend *oldFriend in [change valueForKey:NSKeyValueChangeOldKey]) {
                    if (![observedFriends containsObject:oldFriend]) {
                        [oldFriend removeObserver:self forKeyPath:@"name"];
                    }
                }
            }
            else if ([[change valueForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeReplacement) {
                for (Friend *newFriend in [change valueForKey:NSKeyValueChangeNewKey]) {
                    if (![observedFriends containsObject:newFriend]) {
                        [newFriend addObserver:self forKeyPath:@"name" options:0 context:nil];
                    }
                }
                for (Friend *oldFriend in [change valueForKey:NSKeyValueChangeOldKey]) {
                    if (![observedFriends containsObject:oldFriend]) {
                        [oldFriend removeObserver:self forKeyPath:@"name"];
                    }
                }
            }
    }
}

Cocoa return the number of running application instances

Here’s a little method that returns the number of running instances of your application:

- (int)instanceCount {
    int i = 0;
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) {
        if ([appName isEqualToString:[app localizedName]]) i++;
    }
    return i;
}