【问题标题】:Support multiple iOS SDK versions with Swift使用 Swift 支持多个 iOS SDK 版本
【发布时间】:2017-02-01 07:03:06
【问题描述】:

在我的代码中,NSManagedObject 有以下扩展名:

extension NSManagedObject {
    convenience init(context: NSManagedObjectContext) {
        let name = self.dynamicType.entityName()
        let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
        self.init(entity: entity, insertIntoManagedObjectContext: context)
    }
}

在 Xcode 7 / iOS 9 SDK 中按预期工作。但是,iOS 10 SDK 增加了一个签名相同的方法:

/* Returns a new object, inserted into managedObjectContext. This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.
 */
@available(iOS 10.0, *)
public convenience init(context moc: NSManagedObjectContext)

这让编译器不高兴:Initializer 'init(context:)' with Objective-C selector 'initWithContext:' conflicts with previous declaration with the same Objective-C selector

现在,如果新的 iOS 10 init 可用,我想使用它,如果应用程序在装有 iOS 9 的设备上运行,我想继续使用我的扩展。

有没有一种很好的方法可以在限制现有代码更改的同时实现这一目标?我想在扩展中保留init 的签名。

【问题讨论】:

    标签: ios swift core-data ios10


    【解决方案1】:

    不幸的是,就我而言,您必须以一种或另一种方式更改您的init 的签名。不过,这不一定是很大的变化:

    extension NSManagedObject {
        convenience init(_ context: NSManagedObjectContext) {
            let name = self.dynamicType.entityName()
            let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
            self.init(entity: entity, insertIntoManagedObjectContext: context)
        }
    }
    

    我刚刚删除了context的外部参数名称。现在和新加的不冲突了。

    然后,您可以使用this question中描述的方法检查iOS版本,并调用正确的初始化程序!

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2014-08-19
      • 2018-02-15
      相关资源
      最近更新 更多