我正在开发一个 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/