子类化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];
}
如果出于某种奇怪的原因,您需要属性是可变的,那么您需要使用关联引用来实现:
#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);
}
...