Wednesday, January 26, 2011

NSNotifications

I want to send information between two running applications and I mistakenly thought I could use an NSNotification to do this. [See the UPDATE].

So this post is about the first step, getting an NSNotification to work within a running app. The following is from an Xcode Cocoa-Python app, and in AppDelegate.py we have:


from Foundation import *
from AppKit import *
import objc

class SpeakAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application really did finish launching.")
nc = NSNotificationCenter.defaultCenter()
nc.addObserver_selector_name_object_(
self, "mycallback:", 'love_note', None)

@objc.signature('v@0:@8')
def mycallback_(self,note):
print 'note'
print note.description()

@objc.IBAction
def button_(self,sender):
print sender, 'button'
nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName_object_userInfo_(
'love_note', None, {'path':'xyz'})


There's a button in the window hooked up to the IBAction. I push the button and get:


<NSButton: 0x61c7b0> button
note
NSConcreteNotification 0x6337a0 {name = love_note; userInfo = {
path = xyz;
}}


But I couldn't get it to work between apps, for example with this one compiled in Terminal:


// gcc tell.m -o test -framework Foundation
#import <Foundation/Foundation.h>

int main() {
NSNotificationCenter *nc;
nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"love_note"
object:nil
userInfo:nil ];
return 0;
}


I asked on Stack Overflow (here), and they say I should be using Distributed Objects (here). So I have to look into that.

[ UPDATE: Just substitute NSDistributedNotificationCenter in the code above. It works! ]