在Apple的文档中,有"Subclassing“,有时可能会说它不是特定类的子类。例如,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)
}发布于 2016-11-01 22:01:24
评论已经很好地解决了这个问题,但是要把它整合起来.
子类是在创建带有超类的新类时:
class MyHealthStore: HKHealthStore { /* DON'T DO THIS */ }
let store = MyHealthStore()对于您正在使用的类,来自Apple的指导是避免子类化。他们不保证任何行为,如果你覆盖超类的方法,等等.所以别这么做。
这个基于文档的指导相当于在Swift中将类声明为final。然而,HKHealthStore和大多数其他Apple类都是在ObjC中定义的,它没有任何类似于final关键字的内容,因此此类类仅限于在文档中只说“请不要子类”。
单例是当一个类在运行时有一个共享实例时。有许多Apple类可以这样做,通常通过类方法或类属性公开对共享实例的访问:UIApplication.shared、PHImageManager.default()、ProcessInfo.processInfo (以前的NSProcessInfo.processInfo())等等。
一般来说,子类和单类之间没有冲突。例如,我们欢迎您创建一个UIApplication子类,在这种情况下(假设您的应用程序设置正确),UIApplication.shared将返回您的子类的共享实例。
在这方面,HealthKit有点奇怪。HKHealthStore不是单例类-它没有访问共享实例的类方法,您可以使用默认的初始化器(即调用HKHealthStore())创建它的不同实例。但是,您创建的所有这些实例仍然管理相同的底层共享资源。
https://stackoverflow.com/questions/40366073
复制相似问题