【问题标题】:UNNotificationCategory subclass init issueUNNotificationCategory 子类初始化问题
【发布时间】:2017-05-07 02:34:51
【问题描述】:

我想继承UNNotificationCategory(UserNotifications),因为我想使用枚举而不是硬编码字符串作为类别标识符。 UNNotificationCategory定义里面有一个方便的init

public convenience init(identifier: String, actions: [UNNotificationAction], intentIdentifiers: [String], options: UNNotificationCategoryOptions = [])

我无法为我的子类编写初始化程序。 我知道我不能在子类中指定初始化程序,因为我想调用超类的便利 init。但是我的便利初始化也引发了编译器错误。

代码如下:

enum PushNotificationCategoryIdentifier:String {
}    

convenience init(categoryIdentifier:PushNotificationCategoryIdentifier, actions:[UNNotificationAction], intentIdentifiers:[String], options: UNNotificationCategoryOptions) {
            self.init(identifier: categoryIdentifier.rawValue, actions: actions, intentIdentifiers: intentIdentifiers, options: options)
        }

这会导致错误:self.init 在从初始化程序返回之前未在所有路径上调用

我猜这是因为这个类是在 Objective-C 中实现的,可能他们没有从便利初始化器中调用指定的初始化器(因为 Objective-C 类不必从便利初始化器中调用指定的初始化器)。

但这是否意味着如果我想在 UNNotificationCategory 中编写初始化程序,我就不能继承它?

【问题讨论】:

    标签: ios swift apple-push-notifications usernotifications convenience-methods


    【解决方案1】:

    不,你可以这样做。您必须为此定义init() 方法。现在你只定义了convenience init()。但是你必须在你的子类中定义init()。 当您编写 convenience init() 时,它只是为了以一种简单的方式帮助初始化,但您仍然必须使用 convenience init() 中的语法 init() 调用指定的 init。 你可以在Apple Official Documentation阅读它

    【讨论】:

    • 用什么定义init?我无法初始化 UNNotificationCategory 变量,因为所有变量都只能获取属性。
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多