首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果苹果的文档要求不对类进行子类分类,这是否意味着我们应该将类作为一个单独的类来对待,并且只有一个类呢?

如果苹果的文档要求不对类进行子类分类,这是否意味着我们应该将类作为一个单独的类来对待,并且只有一个类呢?
EN

Stack Overflow用户
提问于 2016-11-01 18:13:24
回答 1查看 147关注 0票数 1

在Apple的文档中,有"Subclassing“,有时可能会说它不是特定类的子类。例如,HKHealthStore有这样的语句在文件中:“与HealthKit中的许多类一样,HKHealthStore类不应该被子类化。”

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

代码语言:javascript
复制
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)
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-01 22:01:24

评论已经很好地解决了这个问题,但是要把它整合起来.

子类是在创建带有超类的新类时:

代码语言:javascript
复制
class MyHealthStore: HKHealthStore { /* DON'T DO THIS */ }

let store = MyHealthStore()

对于您正在使用的类,来自Apple的指导是避免子类化。他们不保证任何行为,如果你覆盖超类的方法,等等.所以别这么做。

这个基于文档的指导相当于在Swift中将类声明为final。然而,HKHealthStore和大多数其他Apple类都是在ObjC中定义的,它没有任何类似于final关键字的内容,因此此类类仅限于在文档中只说“请不要子类”。

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

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40366073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档