Jacksonkr
Jacksonkr

Reputation: 32207

Best way to determine the behavior of a view's containing view

My situation:

ClassA may or may not have a parent of type ClassB. Therefore saying [instanceOfA.superview somethingClassBSpecific]; is half hazardous. Plus, Xocde will get pissy, for good reason.

Is the recommendation here to dispatch a notification, or do some logic on the superview, e.g.,

if([objectOfA.superview respondsToSelector:somethingClassBSpecific] != nil){
    //...
}

Or create a delegate of type ClassB where the situation permits?

Upvotes: 1

Views: 62

Answers (2)

Caleb
Caleb

Reputation: 124997

As is so often the case, it depends. Using the view hierarchy, notifications, and delegation are three different ways that objects can communicate with each other. Deciding which of those (if any) is most appropriate requires thinking about how the objects in question are related to each other.

Notifications provide very loose (nearly zero) coupling between objects. They also provide one-to-many communication -- you post a notification, and every object that's listening for that notification will get the message. But notifications aren't always appropriate; communication is mainly in one direction only, and abusing the notification mechanism can lead to performance problems.

Delegation gives you a way to customize the behavior of an object. The most obvious example is the application delegate. Most every iOS application is based on the same class: UIApplication. UIApplication is exactly the same for every app even though each app does its own thing. The application object uses a delegate to provide the customization that gives the application its unique behavior.

The view hierarchy is another way that (some) objects are connected to each other. If the behavior you're implementing is a) part of a view and b) dependent on that view's relationship with other views, then it may make sense to use the superview and subviews properties.

So, what kind of functionality are you trying to implement?

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

This depends on your logical model. If you have an instance of a class implementing a protocol with optional methods, then using respondsToSelector: is appropriate when you are trying to call one of these optional methods. If you want the method you call to be required, create a do-nothing "guard" in the classes that you pass. Both techniques are valid, it's only a matter of whether or not you'd like your users to be conscious of the need to implement a specific method.

Upvotes: 2

Related Questions