2015-02-06 166 views
2

我想创建NSNotification的子类。 我不想创建一个类别或其他任何东西。继承自NSNotification

正如你可能知道NSNotification类簇,像NSArrayNSString

我知道,集群类的子类需要:

  • 声明自己的存储
  • 覆盖超
  • 覆盖的所有初始化方法超类的原始方法(如下所述)

这是我的子类(没有什么幻想):

@interface MYNotification : NSNotification 
@end 

@implementation MYNotification 

- (NSString *)name { return nil; } 

- (id)object { return nil; } 

- (NSDictionary *)userInfo { return nil; } 

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo 
{ 
    return self = [super initWithName:name object:object userInfo:userInfo]; 
} 
- (instancetype)initWithCoder:(NSCoder *)aDecoder 
{ 
    return self = [super initWithCoder:aDecoder]; 
} 

@end 

当我使用它,我得到一个非凡:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** initialization method -initWithName:object:userInfo: cannot be sent to an abstract object of class MYNotification: Create a concrete instance!' 

还有什么我必须为了从NSNotification继承呢?

+0

不要调用超类初始化 - 例如 - 请参见[如果我想添加类型化属性,请将NSNotification的子类化为正确路由](http://stackoverflow.com/questions/7572059/is-subclassing -nsnotification-the-right-route-if-i-want-to-add-typed-properties) – Paulw11 2015-02-06 01:21:41

+0

感谢您的回应!这就是我一直在寻找的! – 7ynk3r 2015-02-06 01:45:10

回答

1

问题在于试图调用超类初始化程序。你不能这样做,因为它是一个抽象类。因此,在初始化程序中,您只需启动存储。

因为这太可怕了,我最终创建了NSNotification的类别。在那里,我加入了三种方法:

  • 我的自定义通知静态构造函数:在这里,我配置userInfo用作存储。
  • 将信息添加到存储的方法:通知观察者将调用此方法更新userInfo
  • 处理观察者提交的信息的方法:post方法结束后,通知已收集到所需的所有信息。我们只需要处理它并返回它。如果您对收集数据不感兴趣,这是可选的。

最后,该类别只是帮助处理userInfo

谢谢@Paulw11您的评论!