问题
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:
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 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!
回答1:
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
)?
Furthermore, it is no longer "delegation", if you say self.delegate = self
. So I would say it is preferrable to use variant 1.
Thanks for the question.
回答2:
Yes you can do this with no problem. I've a subclass of UITextField which is its own delegate.
回答3:
The first option seems right to me because it doesn't make a ton of sense to subclass CLLocationManager
(#2). What functionality would you be adding to it? If you're not adding anything to it why subclass?
All you care about is encapsulating the messages about location updates. I'd say you're using the delegate/protocol pattern acceptably in the first case.
And Jef is right, there are times where a subclass of another class can be set as its own delegate. Though you need to be careful about how that object responds to certain messages.
来源:https://stackoverflow.com/questions/29054602/does-a-class-being-its-own-delegate-follow-ios-convention