如果我想添加键入的属性,是NSNotification子类化正确的路由? [英] Is subclassing NSNotification the right route if I want to add typed properties?
问题描述
我试图子类化 NSNotification
。
Apple的文档 NSNotification
请注明以下内容:
Apple's docs for NSNotification
state the following:
NSNotification
没有实例变量。因此,
必须子类化NSNotification
并覆盖原始方法
name
,object
和userInfo
。你可以选择你喜欢的任何指定的初始化程序
,但确保你的初始化程序不调用
NSNotification
的实现init
(通过[super init]
)。
NSNotification
不是直接实例化,它的init
方法引发异常。
NSNotification
is a class cluster with no instance variables. As such, you must subclassNSNotification
and override the primitive methodsname
,object
, anduserInfo
. You can choose any designated initializer you like, but be sure that your initializer does not callNSNotification
’s implementation ofinit
(via[super init]
).NSNotification
is not meant to be instantiated directly, and itsinit
method raises an exception.
但这对我并不清楚。是否应该创建这样的初始化程序?
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子类化正确的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!