How do I have a class communicate to it's view controller that something has happened - iphone

I have a viewController that's running my game view. The viewController spawns instances of a Dots, which are subclassed from UIView that are added as subviews to the viewController view. Within the dots class I have certain behavior if they are touched (touchesBegan) but I'd also like touching the dots to add to the score which is a property of the viewController, but I can't see any way to communicate that out without ridiculous workarounds. What am I missing here?

Two options (but not the only ones) are NSNotificationCenter and delegate+protocol.
NSNotificationCenter is simpler to implement and use but not ideal in all cases. The viewController would call addObserver to indicate it is interested in some message. The dots would call postNotificationName to send the message to interested objects. Be sure to call removeObserver in the viewController's dealloc.
Delegate+protocol lets you define a more rigid, well-defined, compiler or runtime verifiable interface between objects. For details, see Protocols in the Objective-C Programming Language.
In your case, I think defining a protocol is the better option. The viewController would make itself the delegate of the dot objects. The dot objects would have a delegate property and call the protocol methods through the delegate property.

Why is the score a property of the ViewController in the first place? I can see having a property for the label that displays the score, but the score itself belongs in some kind of model object.
The advantage of this approach is that you could then use Key-Value Observing (KVO), adding your ViewController as an observer of the model object. In fact, this is pretty much what KVO was designed for: an easy way to notify an arbitrary number of observers about a change to a property.
Reference:
Key-Value Coding Protocol Reference
Key-Value Observing Protocol Reference
Model Object Implementation Guide

Related

UIViewController Intercommunication, is there any kind of method for forcing a UIViewController to update?

I'm creating one UIViewController that operates a calculator interface, while another UIViewController deals with drawing a graph.
The calculator prompts the graph to redraw itself when the user pushes the graph button. The graph then performs a call back to a protocol method on the calculator to get the y value for each given x coordinate.
I'm wondering what the standard way of handling this kind of communication is? I feel like I should be able to call something akin to setNeedsDisplay on a UIViewController (I'm aware this is actually only a UIView method), but I have a feeling I'm going to have to write another protocol with an similar method. Is there some kind of updateViewController method I'm missing?
Ideally I'd like my Calculator UIViewController to only know the graph as a UIViewController while the graph knows the Calculator through a protocol I define.
You have several methods to do that.
Target/Action
Delegates
NSNotificationCenter
KVO (Key Value observing)
In your case, KVO seems to be the best option. Basically, what you graph draws depends on your calculator interface (if I understand correctly) so you are observing some variables (read keys) for change. Look at this document to learn more.
KVO can let you optimize graph drawings as well because you can get previous value, new value etc. Infact, by definition:
Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects.
To my knowledge there is nothing in UIViewController that does exactly what you want. You'll probably need to do some kind of protocol as you suggest and then [yourViewController.view setNeedsDisplay:].
Hope that helps.
There are many ways of doing it and this has been asked here before. For example:
iPhone how to pass data between several viewcontrollers
In your particular case, I would use an NSNotification. Subscribe to it in the viewController that needs to redraw and post a notification from the other one.

UITextView with multiple delegates?

I have a UITextView that points to the File's Owner as its delegate, and I have a number of the delegate functions implemented. However, I would also like to point to a second object (in this case a TextExpander object, http://www.freshblocks.com/tutorials/how-to-add-textexpander-touch-sdk-to-iphone-apps/) also as a delegate. How might this be possible? As far as I know there can only be one delegate in objective-c.
I don't know the specific of TextExpander but he delegate design pattern assumes one and only one delegate. You can't have two delegates for one object.
There are ways around this. You could designate one of the delegates as the primary delegate and implement all the methods in this class. That class could then simple call the secondary delegate for the required methods. This is the simplest approach but does result in the primary delegate becoming tightly coupled with the secondary delegate.
Another approach would be to resolve the messages dynamically and use message forwarding. You would still require the a primary/secondary delegate pattern, but instead of the primary delegate needing to implement all the methods it would simply pass all messages it doesn't respond to onto the secondary delegate. This approach means that the secondary delegate can change by adding/removing additional delegate methods without having to change the primary delegate. The key method is - (id)forwardingTargetForSelector:(SEL)sel. See Objective-C Message Forwarding for a good explanation.
It seems that they solve this in step 5, by setting [textExpander setNextDelegate:self]; before setting the textExpander object as the "primary" delegate of the view.
I don't have the code myself so I haven't tried it, though, and their documentation is... well not.
Just for information: Delegates are not an Objective-C feature, but a design pattern using though Cocoa/Cocoa-touch.
Delegate pattern allow only one object to be notified of the changes of another. The solution to have an intermediate delegate object could be an easy way of doing things.
If you want to keep your code clean and reduce the coupling you might use another pattern known as KVO (Key Value Observing). Apple provides a good guide on how to use it.
In KVO a single object, that needs to be KVC (Key Value Coding) compliant, can notify multiple objects without even knowing about it. It uses an intermediate notifier object (singleton for you application).
Check the Apple doc on KVC + KVO and you shall be able to do what you want.
I have a class with the protocol NSXMLParserDelegate implemented. I call this ParserHelper. I parse a lot of XML which happen to have some tags in all of them and i have about 20 parsers (one for each type of XML), and i didnt want to implement it over and over again.
So, I subclassed my ParserHelper class 20 times, adding in each subclass the required tags/behaviours like CaseAParser, CaseBParser and so on...
I just implement the delegate methods i needed and called it on the superclass once i'm done with the method.
I assume it works on every delegate.
This way, all you need is to make your class a subclass of SMTEDelegateController and implement the methods you need, remembering to call the [super whatEverMethod:andParameters] at the end of your functions and you should be good to go.

Can someone please explain delegates in objective-c?

I have been using Objective-C for a while and pretty much understand most of its features. However, the concept of delegates eludes me. Can someone please give a succinct and easy to comprehend explanation of what delegates are, how they are used in the iPhone SDK, and how I can best make use of them in my own code?
Thank you!
There are a couple main reasons to use delegates in Objective-C, which are subtly different:
Enhancing the base functionality of a framework class. For example, a UITableView is pretty boring on its own, so you can give it a delegate to handle the interesting bits (creating table cells, adding text to section headers, what have you). This way, UITableView never changes, but different table views can look and act very differently.
Communicating to parent objects in your dependency hierarchy. For example, you may have a view with a button that the user may push to do something that affects other views. The view will have to send a message to its parent view, or perhaps the view controller, so that it can create or destroy or modify other views. To do this you'd pass the parent object into your view, most likely through a protocol, as a weak reference (in Objective-C, an assign property). The view could then send any message declared in the protocol to the parent, or delegate, object.
This approach need not involve views. For example NSURLConnection passes event back to its delegate, which may be the object that created it, using this mechanism.
Essentially, all a delegate is, is an object that accepts feedback from another object. Put simply, when stuff happens to an object, it tells its delegate (assuming it has one).
For instance, lets say I have a UIViewController with a UITextView placed in the middle of the view. I set up my UIViewController to be the delegate of the UITextView. Then, when certain actions are performed on the text view (begin editing, text changes, end editing, etc), it tells it's delegate so it can do whatever logic it needs to do, like spell checking every time characters change, or dismissing the keyboard when it receives a return key press.
Delegate methods perform a similar function to callback functions in C.
Hope that makes sense :)
Best and simple concept I got from a Lynda.com Tutorial was: When you set a Delegate it means you have been given work to do. So, if you want to use methods that are written in a protocol method, you must implement them by searching in the Delegate Class Reference and using them. I hope it helped.
By the way, Delegates are excellents. They are your friends. They have been made to make your life as a programmer much easier.

iPhone Programming - How do I programmatically make a view that requires two delegates?

Here is my dilemma. I would like to have a text box and a button. The user types in text and then presses the button. Once the button is pressed, a text message window (using MFMessageComposeViewController) comes up. I don't know how to set this up. The problem is that the TextBox will require a delegate (UITextFieldDelegate) and the MFMessageComposeViewController will require an MFMessageComposeViewControllerDelegate. How can I have a .h file that declares a view that is more than one delegate?
I'm new to iPhone programming so any help on how to have an interface view that handles more than one delegate (so that I can have multiple types of controls in my view) would be really helpful!
A delegate does not need to be a view. Indeed, in most cases it probably shouldn't be. Often you will make a controller object the delegate, although this depends a lot on what you're doing.
The delegate protocols you need (MFMessageComposeViewControllerDelegate and UITextFieldDelegate) are quite distinct, so a single object can readily implement the methods of both without any confusion. But even if you are the same delegate type for several objects, the methods will be passed a pointer to the calling object so you can decide what to do case-by-case if necessary.
If you just mean how do you declare your class as implementing both protocols, you would do this:
#interface MyDelegate : NSObject <MFMessageComposeViewControllerDelegate, UITextFieldDelegate>
{
...
}
...although this presupposes that the protocols are formally required, which I don't think is the case here. In which case such a protocol list is unnecessary.
Otherwise, I probably am not understanding your question...
EDIT: OK, it seems like what you're looking for is how to link up the delegates at runtime. This varies according to the particular class, but for MFMessageComposeViewController you do this:
MFMessageComposeViewController* composer = ...;
id<MFMessageComposeViewControllerDelegate>* delegate = ...;
composer.messageComposeDelegate = delegate;
Easy, no? In this case the protocol is required, so you'd have to include it in the interface as described previously.
In general, if an object uses a delegate for anything, it will have a property or a method to allow you to set it, which you'll find in the documentation. Eg, in this case: Properties for MFMessageComposeViewController.
Note that delegate properties are conventionally weak references, so the objects in question need to be retained somewhere in your application.

Does it make sense that there may be more than one class that conforms to the UIApplicationDelegate protocol in an iPhone App?

I think I've understood what that Delegate is supposed to do. If a class conforms to that protocol, it tells the underlying system: "Hey man, I am the UIApplication object's delegate! Tell me what's up, and I may tell you what to do!".
What, if multiple classes implement that? Is that possible? Does that make any sense?
While you could implement multiple classes that conform to the UIApplicationDelegate protocol only one, the first, would receive these messages.
Implementing a protocol to create a delegate is only one part of the equation. That delegate then has to be registered with the code that's generating the messages and these systems generally only support one delegate.
In the case of UIApplication you can change the delegate using the 'delegate' property in the UIApplication shared class but this will replace the original delegate, not add an additional one.
If you need to broadcast UIApplication level messages to other systems then this is functionality you should add to your existing delegate.
You can implement multiple classes that adopt the UIApplicationDelegate protocol, but only one can be the actual delegate at any given time. It's set by [UIApplication sharedApplication].delegate, which is normally set up by the main NIB file by an outlet connection.
Just conforming to the protocol doesn't set your object as the delegate, you need to do that explicitly either in the nib or in code. As already mentioned, only one object can be a delegate at one time. Having multiple delegates may make sense in some cases-- for example if you have a table view that displays two sets of data, you could make two delegate and datasource objects for it, and switch between them as needed. It probably doesn't make sense to do this for the application's delegate though, since the code there is pretty specific.
Keep in mind that sometimes an object will send notifications in addition to calling delegate methods. A lot of time it looks like they're the same thing, since the object will automatically subscribe your delegate to the notification if it includes a certain method signature. The key difference though is that other objects besides the delegate can also subscribe to these notifications, so you can hook them up to multiple objects at once.
As Daniel Dickson stated:
You can implement multiple classes that adopt the UIApplicationDelegate protocol, but only one can be the actual delegate at any given time. It's set by [UIApplication sharedApplication].delegate, which is normally set up by the main NIB file by an outlet connection.
... but know that you can swap these out at runtime if you need to. I recently looked at using this technique as a way of merging two applications developed by different parties that could not share source code or refactor; yet needed to co-locate under a single icon on the device.