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.

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];    

Trim leading and trailing whitespaces from NSMutableAttributedString

You can use NSString’s rangeOfCharacterFromSet method to search the string for whitespace and newlines:

// Trim leading whitespace and newlines.
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange range           = [attString.string rangeOfCharacterFromSet:charSet];
while (range.length != 0 && range.location == 0)
{
    [attString replaceCharactersInRange:range
                             withString:@""];
    range = [attString.string rangeOfCharacterFromSet:charSet];
}

// Trim trailing whitespace and newlines.
range = [attString.string rangeOfCharacterFromSet:charSet
                                   		  options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) == attString.length)
{
    [attString replaceCharactersInRange:range
                             withString:@""];
    range = [attString.string rangeOfCharacterFromSet:charSet
                                              options:NSBackwardsSearch];
}

NSView apply grayscale transform filters

Need to apply an overall effect to your NSView? It’s pretty easy using QuartzCore filters. Here’s an example applying a grayscale effect first and then a gamma effect on top.

EDIT: You need to enable layer backing for this to work.

#import <QuartzCore/QuartzCore.h>

- (void)initWithFrame:(NSRect)frame
{
   self = [super initWithFrame:frame];
   if (self) {
      self.wantsLayer = YES;  // Enable layer backing.
   }
   return self;
}

- (void)addFilters 
{
   if (!_filtersAdded) {
        // Yes, apply grayscale filter
        CIFilter *filt = [CIFilter filterWithName:@"CIColorMonochrome"]; // CIImage
        [filt setDefaults];
        [filt setValue:[CIColor colorWithRed:.3 green:.3 blue:.3 alpha:1] forKey:@"inputColor"];
        CIFilter *filt2 = [CIFilter filterWithName:@"CIGammaAdjust"]; // CIImage
        [filt2 setDefaults];
        [filt2 setValue:[NSNumber numberWithFloat:0.3] forKey:@"inputPower"];    
        [self setContentFilters:[NSArray arrayWithObjects:filt, filt2, nil]];
    }
   else {
      [self setContentFilters:[NSArray array]];
   }

   _filtersAdded = !_filtersAdded;
}