objective-c - NSNotificationCenter 选择器无法与其 NSNotification 一起使用

标签 objective-c cocoa notifications nsnotifications

我正在开发一个 Cocoa 项目,其中包含一些 C(我知道,objc 包含 C...),并且正在尝试理解 NSNotificationCenter。情况如下:

我有一个声明为 typedef struct {/*code here*/} structName;

的结构

在我的 - (id)init 方法中,我有

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selName:) name:@"notName" object:nil];

我有一个回调函数:

int callback(/*args*/) {
    structName *f = ...
    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notName" object:[[NSValue valueWithPointer:f] retain]];
    [autoreleasepool release];
}

然后是我的选择器:

- (void)selName:(NSNotification *)note
{
    NSLog(@"here");
    NSLog(@"note is %@", note);
}

现在,如果我注释掉第二个 NSLog,一切似乎都正常(即打印“here”)。但如果我将其保留,则 NSNotification 似乎不起作用。但这似乎违背了 NSNotification 的对象、userInfo 等的目的。

我做错了什么?如何修复它以便可以访问我的 structName f

@内森 好的,现在我有了

NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSValue valueWithPointer:f] forKey:@"fkey"];//f, not &f. I had a typo in the OP which I fixed.
[[NSNotificationCenter defaultCenter] postNotificationName:@"notName" object:nil userInfo:[dict retain]];

...但问题仍然存在。这有可能与我修正的拼写错误有关吗?

编辑:

即使将上面两行更改为

,问题仍然存在
[[NSNotificationCenter defaultCenter] postNotificationName:@"notName" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSData dataWithBytes:f length:sizeof(structName)] forKey:@"fkey"]];

最佳答案

Works for me.你做了什么不同的事情?

关于objective-c - NSNotificationCenter 选择器无法与其 NSNotification 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1055530/

相关文章:

ios - 如何使用 NSURLConnection 获取呈现的 javascript 源

xamarin - 本地通知插件 - 图像/ Logo

ruby-on-rails - 在 Rails 中进行通知

android - 如何扩展只有一个附加行的 InboxStyle 通知?

ios - 在WatchKit中解析查询

iphone - 返回使用 GCD 在单独线程中检索到的值

ios - 使用 iOS SDK 在 facebook 上分享视频

objective-c - 关闭 UITableView 静态单元格中的复选标记

cocoa - 在 Cocoa(不是 Cocoa Touch)中的 View 之间切换

cocoa - 将选择器存储为 NSDictionary 中的值