1

在 Apple 的文档中有“子类化注释”,有时可能会说不子类化特定类。例如,HKHealthStore在其文档中有这样的措辞:“像 HealthKit 中的许多类一样,HKHealthStore 类不应该被子类化。”。

但是,在编译的教程中,我们创建了 HKHealthStore 类的一个实例并将其用于引用 HealthStore 函数。例如:

let currentHealthStore = HKHealthStore()

if HKHealthStore.isHealthDataAvailable(){
            //The following is for if HealthKit is supported in this device
            print("Yes, this iPhone 6 Plus supports Health Information")

            let typesToRead = dataToRead()
            let typesToWrite = dataToWrite()
            currentHealthStore.requestAuthorization(toShare: typesToWrite as? Set<HKSampleType>, read: typesToRead as? Set<HKObjectType>, completion: { (success, error) -> Void in

                if success{

                    // We will update UI to preview data we read.
                    DispatchQueue.main.async(execute: { () -> Void in

                        self.loadView()
                    })

                }
                else{

                    print("User didn't allow HealthKit to access these read/write data types")
                }

            })
        } else {
            let alertController = UIAlertController(title: "Warning", message: "HealthKit is not available in your device!", preferredStyle: UIAlertControllerStyle.alert)

            alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))

            self.present(alertController, animated: true, completion: nil)
        }
4

1 回答 1

1

评论已经很好地解决了这个问题,但是要把它放在一起......


子类化是当您使用超类创建新类时:

class MyHealthStore: HKHealthStore { /* DON'T DO THIS */ }

let store = MyHealthStore()

对于您正在使用的类,Apple 的指导是避免子类化。他们不保证如果您覆盖超类的方法等会发生什么行为......所以不要这样做。

这个基于文档的指南等同于final在 Swift 中声明一个类。但是,HKHealthStore大多数其他 Apple 框架类都是在 ObjC 中定义的,它没有任何类似final关键字的东西,因此此类类仅限于在文档中说“请不要子类化”。


单例是指类在运行时具有单个共享实例。有许多 Apple 框架类可以做到这一点,通常通过类方法或类属性公开对共享实例的访问:UIApplication.sharedPHImageManager.default()ProcessInfo.processInfo(以前NSProcessInfo.processInfo()的 )等。

一般来说,子类化和单例之间没有冲突。例如,欢迎您创建一个UIApplication子类,在这种情况下(假设您的应用程序设置正确),UIApplication.shared将返回您的子类的共享实例。

HealthKit 在这方面有点奇怪。HKHealthStore不是一个单例类——它没有访问共享实例的类方法,您可以使用默认初始化程序(即调用HKHealthStore())创建它的不同实例。但是,您创建的所有这些实例仍然管理相同的底层共享资源。

于 2016-11-01T22:01:24.033 回答