0

我有一个工作应用程序,当用户在窗口中按下一个按钮时,它会向自身发送一个 NSNotification(Xcode 使用 PyObjC):

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)
            #self, "mycallback:", None, 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'})

(一个细节:签名可能不完全正确,但它有效)。

让它运行。现在我想弄清楚如何从另一个应用程序向这个应用程序发送相同的通知,例如:

// 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;
}

我注意到,如果我在第一个应用程序中取消注释该行,那么我会收到很多其他通知,但它们都来自与我的应用程序相关的事件。我从来没有听到任何来自外面的声音。如何在进程之间发送通知?然后,有没有办法从命令行发送通知?谢谢。

更新:只需替换上面的 NSDistributedNotificationCenter 即可,示例有效。

4

1 回答 1

3

我不相信有一种方法可以使用 NSNotificationCenter 在两个应用程序之间进行通信。我以前没有使用过它,但我相信两个应用程序通信更像是分布式对象的工作。

来自 Apple 的文档:

每个进程都有一个默认通知中心,您可以使用 NSNotificationCenter +defaultCenter 类方法访问该通知中心。此通知中心在单个进程中处理通知。对于同一台机器上的进程之间的通信,使用分布式通知中心(参见“NSDistributedNotificationCenter”)。

编辑

看起来NSDistributedNotificationCenter也可以做您正在寻找的事情,而无需深入了解分布式对象。

于 2011-01-26T21:11:54.753 回答