我正在尝试将NSNotification
子类化。
Apple的NSNotification
文档说明以下内容:
但这对我来说还不清楚。我应该像这样创建一个初始化器吗?
-(id)initWithObject:(id)object
{
return self;
}
最佳答案
子类化NSNotification
是一种非典型操作。我想我在过去几年中只看过一两次。
如果您希望随通知一起传递东西,那就是userInfo
属性的用途。如果您不喜欢直接通过userInfo
访问内容,则可以使用类别来简化访问:
@interface NSNotification (EasyAccess)
@property (nonatomic, readonly) NSString *foo;
@property (nonatomic, readonly) NSNumber *bar;
@end
@implementation NSNotification (EasyAccess)
- (NSString *)foo {
return [[self userInfo] objectForKey:@"foo"];
}
- (NSNumber *)bar {
return [[self userInfo] objectForKey:@"bar"];
}
@end
您也可以使用这种方法来简化
NSNotification
的创建。例如,您的类别还可以包括:+ (id)myNotificationWithFoo:(NSString *)foo bar:(NSString *)bar object:(id)object {
NSDictionary *d = [NSDictionary dictionaryWithObjectsForKeys:foo, @"foo", bar, @"bar", nil];
return [self notificationWithName:@"MyNotification" object:object userInfo:d];
}
如果出于某种奇怪的原因,您需要使属性可变,那么您需要使用associative references来实现:
#import <objc/runtime.h>
static const char FooKey;
static const char BarKey;
...
- (NSString *)foo {
return (NSString *)objc_getAssociatedObject(self, &FooKey);
}
- (void)setFoo:(NSString *)foo {
objc_setAssociatedObject(self, &FooKey, foo, OBJC_ASSOCIATION_RETAIN);
}
- (NSNumber *)bar {
return (NSNumber *)objc_getAssociatedObject(self, &BarKey);
}
- (void)setBar:(NSNumber *)bar {
objc_setAssociatedObject(self, &BarKey, bar, OBJC_ASSOCIATION_RETAIN);
}
...
关于objective-c - 如果要添加类型化的属性,将NSNotification子类化是正确的方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7572059/