Search code examples
objective-ccocoacocoa-sheet

beginSheet: block alternative?


Didn't Snow Leopard introduce some alternative to the old beginSheet: method that allows using a block to do the finishing stuff? I don't like having it in another callback method.


Solution

  • Never mind. I found what I'm looking for at these two sites:

    http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html, http://www.cocoabuilder.com/archive/cocoa/281058-sheets-blocks-and-garbage-collector.html

    In fact, this is the code, and it's fully compatible with both GC and non-GC:

    @implementation NSApplication (SheetAdditions)
    
    - (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow didEndBlock:(void (^)(NSInteger returnCode))block
    {  
      [self beginSheet:sheet
        modalForWindow:docWindow
         modalDelegate:self
        didEndSelector:@selector(my_blockSheetDidEnd:returnCode:contextInfo:)
           contextInfo:Block_copy(block)];
    }
    
    - (void)my_blockSheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
    {
      void (^block)(NSInteger returnCode) = contextInfo;
      block(returnCode);
      Block_release(block);
    }
    
    @end