2

我想创建一个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

4

1 回答 1

2

问题是试图调用超类初始化程序。你不能这样做,因为它是一个抽象类。所以,在初始化器中你只需要初始化你的存储。

因为这太可怕了,所以我最终创建了一个类别NSNotification。在那里我添加了三种方法:

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

归根结底,它只是一个帮手处理的类别userInfo

感谢@Paulw11的评论!

于 2015-02-06T19:09:34.597 回答