问题描述
我试图子类化 NSNotification
。
Apple的文档 NSNotification
请注明以下内容:
Apple's docs for NSNotification
state the following:
但这对我并不清楚。是否应该创建这样的初始化程序?
But this isn't clear to me. Should I create an initializer like this?
-(id)initWithObject:(id)object
{
return self;
}
推荐答案
子类 NSNotification
是一个非典型操作。我想我在过去几年里只看过它一次或两次。
Subclassing NSNotification
is an atypical operation. I think I've only seen it done once or twice in the past few years.
如果你想与通知一起传递,那就是 userInfo
属性。如果您不喜欢直接通过 userInfo
访问内容,您可以使用类别来简化访问:
If you're looking to pass things along with the notification, that's what the userInfo
property is for. If you don't like accessing things through the userInfo
directly, you could use a category to simplify access:
@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
创建。例如,您的类别也可以包括:
You can also use this approach to simplify NSNotification
creation. For example, your category could also include:
+ (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];
}
如果由于某种奇怪的原因, ,则您需要使用完成:
If, for some strange reason, you'd need the properties to be mutable, then you'd need to use associative references to accomplish that:
#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);
}
...
这篇关于如果我想添加键入的属性,是NSNotification子类化正确的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!