类作为其自己的委托是否遵循iOS约定? [英] Does a class being its own delegate follow iOS convention?

查看:48
本文介绍了类作为其自己的委托是否遵循iOS约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这个问题听起来很主观,但是我认为它应该有一个明确的答案。我有一个要管理我的核心位置逻辑的类 LocationManager。我有两个选择:

Sorry this question may sound "subjective" but I think it should have a pretty definitive answer. I have a class "LocationManager" that I want to manage my Core Location logic. I have two options:


  1. LocationManager具有引用CLLocationManager实例的强大属性。 LocationManager是CLLocationManager的委托,并从中接收位置更新。

  1. LocationManager has a strong property referencing an instance of CLLocationManager. LocationManager is a delegate of CLLocationManager and receives location updates from it as such.

LocationManager是CLLocationManager的子类,并表示self.delegate = self,因此它可以接收自己的位置更新。

LocationManager is a subclass of CLLocationManager, and says self.delegate = self so that it can receive its own location updates.

我很好奇以下哪个选项被认为是正确的选择这样做,我确信必须有一种首选的方法。谢谢!

I'm curious which of these options is considered the "right" thing to do, I'm sure that there must a be a preferred way. Thanks!

推荐答案

子类化 CLLocationManager 并将其委托设置为self不应之所以这么做,是因为它违反了 CLLocationManager 的合同。当前定义类时,它具有 delegate 属性。该属性用作合同,规定您可以将此属性设置为其他对象,并且该对象将接收委托通知。如果您将 CLLocationManager 子类化(我们称它为 MyLocationManager ),并且对象的委托属性指向自身,则您很可能会创建这样一种情况,即 MyLocationManager 仅在用户使用 delegate 财产用于他自己的目的。从用户的角度来看, MyLocationManager CLLocationManager ,而没有可用的 delegate 属性。这违反了 Liskovs替代原则,顺便说一句。这里要问的问题是:如果某些 ViewController 类决定使用它并让它的委托属性是否指向自身( ViewController )?

Subclassing CLLocationManager and setting its delegate to self should not be done because it breaks the contract of CLLocationManager. As the class is currently defined, it has a delegate property. This property serves as a contract which states that you may set this property to some other object, and this object will receive delegate notifications. If you subclass CLLocationManager (let's call it MyLocationManager), and if the delegate property of the object points to itself, then you will most likely create a situation where MyLocationManager only works as promised if the user does not use the delegate property for his own purposes. From a users point of view, MyLocationManager is a CLLocationManager without a usable delegate property. This violates Liskovs Substitution Principle, btw. The question to ask here is: would MyLocationManager still work, if some ViewController class decides to use it and have its delegate property point to itself (the ViewController)?

此外,如果您说 self.delegate = self ,它不再是委托。因此,我想建议使用变体1。

Furthermore, it is no longer "delegation", if you say self.delegate = self. So I would say it is preferrable to use variant 1.

感谢您提出问题。

这篇关于类作为其自己的委托是否遵循iOS约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆