How do I have a class communicate to it's view controller that something has happened
I have a v开发者_如何学JAVAiewController 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
精彩评论