我正在开发一个包含一些 C 的 Cocoa 项目(我知道,objc 包含 C ...),并且正在尝试理解NSNotificationCenter
s. 情况如下:
我有一个声明为的结构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
,一切似乎都正常(即打印了“这里”)。但如果我把它留在里面,NSNotification
似乎没有任何作用。但这似乎违背了NSNotification
.
我做错了什么,我该如何解决它,以便我可以访问我的structName f
?
@Nathan 好的,所以现在我有了
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"]];