Sending an event up the UIResponder chain? - objective-c

I just created a custom UIViewController with some user actions like touch. I would like to handle the user interaction in the parentObject. In other words the one that created the ViewController.
From other languages I am used to use Events that are pushed up. So my parent object would have some kind of listener on the reference of the ViewController object it can react to.
How would that type of interaction handled by Objective C?

This can be done by 1) responder chain, 2) notifications and 3) delegates.
All UI objects form the responder chain, starting from the currently focused element, then it's parent view and so on, usually until the application object. By sending action to the special First Responder object in your nib, you'll throw it down the responder chain until someone handles it. You can use this mechanism for firing events without knowing who and when will handle them. This is similar to HTML event model.
Notifications send by NSNotificationCenter can be received by any number of listeners. This is the closest analog to e.g. C# events.
Delegates is the simplest mechanism of sending event to one single object. The class declares weak property named delegate that can be assigned with any object, and a protocol that this object is supposed to implement. Many classes use this approach; the main problem is that you can't have more than one listener this way.

you should look into delegations/delegate for interactions between two viewControllers. You need to understand how it works first.
https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html

It sounds like you need to implement a delegate protocol, which will allow your 'child' view controller to communicate back to it's 'parent'
See http://developer.apple.com/library/ios/#documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html

Related

What is the difference between beginTrackingWithTouch and touchesBegan?

Can someone please explain the high-level difference between these two methods? In particular, when would you use one over the other, and is there any overlap in terms of the purposes of these methods?
They seem like they serve the same purpose but don't appear to be related at all in documentation, and this has me confused.
beginTrackingWithTouch:withEvent:
1) subclass UIControl
2) Sent to the control when a touch related to the given event enters the control’s bounds.
3) To provide custom tracking behavior (for example, to change the highlight appearance).
To do this, use one or all of the following methods: beginTrackingWithTouch:withEvent:, continueTrackingWithTouch:withEvent:, endTrackingWithTouch:withEvent:
touchesBegan:withEvent:
1) subclass UIResponder
2) Tells the receiver when one or more fingers touch down in a view or window.
3) There are two general kinds of events: touch events and motion events.
The primary event-handling methods for touches are touchesBegan:withEvent:, touchesMoved:withEvent:, touchesEnded:withEvent:, and touchesCancelled:withEvent:.
The parameters of these methods associate touches with their events—especially touches that are new or have changed—and thus allow responder objects to track and handle the touches as the delivered events progress through the phases of a multi-touch sequence.
Any time a finger touches the screen, is dragged on the screen, or lifts from the screen, a UIEvent object is generated. The event object contains UITouch objects for all fingers on the screen or just lifted from it.
Having just run into this today, I think the key difference is that beginTrackingWithTouch and friends are only for tracking - not anything else - in particular not for target/action handling. So if you override touchesBegan, then you'd also be responsible for calling sendActionsForControlEvents when touches ended. But if you use beginTrackingWithTouch, that's handled for free.
I discovered this by implementing beginTrackingWithTouch (for a custom button control) thinking it was just a sideways replacement for handling touchesBegan. So in endTrackingWithTouch, I called sendActionsForControlEvents if touchInside was true. The end result was that the action was called twice, because first the builtin mechanism sent the action, then I called it. In my case, I'm just interesting in customizing highlighting, so took out the call to sendActionsForControlEvents, and all is good.
Summary: use beginTrackingWithTouch when all you need to do is customize tracking, and use touchesBegan when you need to customize the target/action handling (or other low-level details) as well.
If I properly understand Apple documentation:
beginTracking:
Use the provided event information to detect which part of your control was hit and to set up any initial state information
So, it's more for control state configuration.
touchesBegan:
Many UIKit classes override this method and use it to handle the corresponding touch events
This method is more for touch event handling.

How does forwardingTargetForSelector: work?

I have a UIBarButtonItem. When it receives a message it cannot handle, I want it to forward that message to a particular view controller.
I thought I might be able to accomplish this using the bar button item's forwardingTargetForSelector: method, but apparently no such property is found on objects of type UIBarButtonItem. (Point of terminology: Does that mean forwardingTargetForSelector: is a private property? edit: Wait, I think I'm confused... methods with a colon at the end aren't properties... so can you ever make public a method (like a getter/setter) to which parameters are passed?)
And does that mean that in order to set the value of forwardingTargetForSelector: I must do it from within the .m file of the object for which I want to set it? Which would mean that I would have to subclass my UIBarButtonItem?
And if so, why is this not a public property of NSObjects?
And moreover, what's the best way to achieve my forwarding goal, preferably avoiding subclassing?
additional information:
It all stems from my inclination to reuse a single action in response to various instances of an identical button being pressed. The action is currently contained in my delegate (see How should I implement [almost] identical actions used throughout various VCs? (Answer: use a category)) and varies only in that it should send a presentViewController message to the view controller that instantiated the button that sent the action. Thus, in the action, I can send a presentViewController message to sender, which is an instance of the button, and I want to be able to forward that message to the view controller that created that instance of the button, which I can do if I set each button's forwarding property immediately after it is instantiated in its respective view controller.
I hoped to avoid the "why" just to make the question shorter, but there ya go.
forwardingTargetForSelector: is not really a property; it's more like a question the runtime asks an instance when the instance doesn't respond to a message.
It can't be a property in the #property/declared-property sense, because each selector could have a different target; there would need to be a mapping behind it. That's just not how declared properties work.
UIBarButtonItem descends from NSObject, and it inherits this method along with all the others, but you can't "set" the forwarding target for a selector from outside an instance (without creating some other machinery to allow you to do so, anyways -- possible, but not available by default).
In order to utilize this method, yes, you have to implement it in the class that is doing the forwarding. This does indeed mean subclassing. It also means that the forwarding instance needs to have a reference to the object to which it is forwarding; this requires careful design.
forwardingTargetForSelector: is all but certainly not the correct way to achieve whatever your goal is. In general, in fact, it's a bit esoteric.
I'm not sure exactly what problem you're trying to solve ("making a button forward messages it doesn't respond to" is still rather general -- in particular, why is that necessary?), so it's hard to be more precise.

NSNotifications vs delegate for multiple instances of same protocol

I could use some architectural advice. I've run into the following problem a few times now and I've never found a truly elegant way to solve it.
The issue, described at the highest level possible:I have a parent class that would like to act as the delegate for multiple children (all using the same protocol), but when the children call methods on the parent, the parent no longer knows which child is making the call.
I would like to use loose coupling (delegates/protocols or notifications) rather than direct calls. I don't need multiple handlers, so notifications seem like they might be overkill.
To illustrate the problem, let me try a super-simplified example:
I start with a parent view controller (and corresponding view). I create three child views and insert each of them into the parent view. I would like the parent view controller to be notified whenever the user touches one of the children. There are a few options to notify the parent:
Define a protocol. The parent implements the protocol and sets itself as the delegate to each of the children. When the user touches a child view, its view controller calls its delegate (the parent). In this case, the parent is notified that a view is touched, but it doesn't know which one. Not good enough.
Same as #1, but define the methods in the protocol to also pass some sort of identifier. When the child tells its delegate that it was touched, it also passes a pointer to itself. This way, the parent know exactly which view was touched. It just seems really strange for an object to pass a reference of itself.
Use NSNotifications. The parent defines a separate method for each of the three children and then subscribes to the "viewWasTouched" notification for each of the three children as the notification sender. The children don't need to attach themselves to the user dictionary, but they do need to send the notification with a pointer to themselves as the scope.
Same as #4, but rather than using separate methods, the parent could just use one with a switch case or other branching along with the notification's sender to determine which path to take.
Create multiple man-in-the-middle classes that act as the delegates to the child views and then call methods on the parent either with a pointer to the child or with some other differentiating factor. This approach doesn't seem scalable.
Are any of these approaches considered best practice? I can't say for sure, but it feels like I'm missing something more obvious/elegant.
Your #2 is the standard Cocoa pattern for delegates. Each message of the delegate protocol takes the object as the first argument. For example, in UITableViewDelegate, you find methods like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
When a table view sends this message to its delegate, it sends itself (the table view) as the first argument. If the delegate object is the delegate of multiple table views, it can use the first argument to figure out which table view sent the message.
When there are no other arguments, the message still takes the object as an argument, as in this UITableViewDataSource method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
You will find this pattern all over the Cocoa Touch framework; UIPickerViewDelegate, UIImagePickerControllerDelegate, and UINavigationControllerDelegate are just a few examples.
You should follow the standard pattern unless you have a compelling reason not to. Following the convention will make it easier for others (and future you) to understand your code.

Using Protocols in Objective C to Transfer Data Between Different Objects?

Hey guys, I currently have a root table view which has a toolbar at the bottom and has labels and a refresh button within it, much like the Mail app's toolbar. This root table view controller obtains data from a server by allocating and initializing a DataUpdater class. Within this class are the NSURLConnection delegate methods that are called while communicating with the server.
As you can probably guess, I need to know when certain (delegate) functions are called within the DataUpdater class and the values of the parameters passed to these delegate functions so that I can update the labels on the toolbar accordingly (i.e. Connecting..., Updated, etc).
The problem I am having is determining how to notify the root table view controller of what is going on in these delegate methods. Would I use protocols, if so how? I have been skimming the documentation and don't quite see how I would get this effect. Or would you suggest I implement my program another way?
Thanks in advance!
A protocol is a kind of contract that says: I promise to provide the non-optional methods defined in the protocol, and maybe even the optional ones. It's purpose is like Java interfaces: to work around missing multiple-inheritence.
The delegate pattern in Objective-C normally works like this: you define a protocol, and then in your class, you define a variable like id<MyProtocol> myDelegate; and define a setter and maybe getter (either via normal methods, e.g. - (void)setDelegate:(id<MyProtocol>)aDelegate; or via properties.
Note that the delegate is not retained ! So if you work with a property, you need the assign option, not retain.
Now back in your class, you check whether myDelegate is nil and if not, you can directly call its non-optional methods. If you want to call an optional method, you first need to verify its presence via respondsToSelector:.
So if you decide to use the delegate pattern, you need to define a protocol, add that protocol to your root table view controller, implement the necessary methods there, and make sure to call [foo setDelegate:self]; or something similar to inform your other class that the root table view controller is the delegate. And of course implement the delegate calls in your class.
Edit:
An alternative might be to use NSNotifications, BTW. The advantage of notifications is that you can have multiple objects listen and react to them. The disadvantage is that you cannot (directly) pass values back. For example, you can define a delegate method that asks the delegate whether to do something or not. That's not possible with notifications, it's more like shouting into a room instead of having a one-to-one conversation.
DarkDust's answer about protocols is fine but I would like to add some things to it.
One underlying thing that is often forgotten when it comes to delegation is object ownership. When a program is running it creates a tree of objects. Its root object is the application delegate and for example it owns a navigation controller, which owns the individual view controllers, which own the view and the view owns its subviews and so on.
Often the question comes up: "Why is the delegate not retained, just assigned?" The problem is that if you send a message to a deallocated object the program crashes. So how do you make sure the delegate stays around? The answer is object ownership.
I give you an example: a UITableView and its data source which is the TableViewController which is nothing but a delegate. The TableViewController holds a reference with its view property to the UITableView, so it owns the TableView. That means when the tableView is alive there must also be its parent object present, which is the UITableView's delegate. So there is no danger that the delegate goes away somehow.
In the end it is again all about memory management.
Take home message is: think upfront about object ownership will make your program mode modular, easier to maintain and will lead to a looser coupling between individual objects.

How provide own Sent Messages in Interface Builder

I cannot find documents about the way, in which Interface Builder determines the Sent Message outlets for the graphical connections between components triggering events and messages of other components.
I want to generate components encapsulating Finite State Automata. The input part is simple, just define IBAction messages and you can connect them in in Interface Builder. The tricky part is obviously the other end of such connections.
I want to provide for each event triggered by the FSM a distinct outlet, like the 'selector' outlet of a NSButton (listed under 'Sent Messages' on the 'Connections' tab of the inspector).
How do I specify such interfaces programmatically and can I specify more than one of these?
Or is this approach not suitable; would Notifications be a better way? (I am used graphical connections from Visual Age and Parts, so I would prefer them, but in Interface Builder, the support for such connections seems somehow limited).
Thanks in advance
The first part of my question has been ansered in the question 'Send An Action Cocoa - IBAction'. I am still looking for a possibility to define more than one 'Sent Message'.
When you implement your method using IBActions, the object that generated the message (the sender) is passed to the message. So if I have a button on my interface that says "Logout" and an action on some controller object named logout: and I have wired these up, the method receives the instance of the button that triggered it. For example:
- (void)logout:(id)sender
{
// sender is the instance of whichever wired button triggered
// this action. We just NSLog() it for now.
NSLog(#"-[%# logout:%#]", self, sender);
}
Other objects may call this action as well, and may pass themselves as the sender or may pass nil. The details of this would be left up to you as the designer.