Event Handling Without Subclassing - objective-c

I've recently watched some Lynda tutorials on how to program in Objective C and Cocoa. Coming from a PHP and C# background, one thing caught my attention - event handling. As I was watching the tutorials, the mentor was going through subclassing in order to attach to events.
He eventually discussed creating delegates and attaching to the events that way - better, but still not near as easy as C#. However, I later found out that not everything has a delegate, which makes things even more difficult.
I've been searching the Internet for a way to handle events without making a subclass so that I don't end up with this application that has an enormous amount of files, but to no avail.
I'm specifically trying to attach to a mouseLeave or mouseOut event for a NSSlider object so that I can hide a label once it's finished sliding.
Is there some way I can attach to the event without doing any subclassing, or is creating subclass after subclass something that I should just get used to?

There are a few ways for event-handling.
Like you said, subclassing, is probably the easiest.
Using delegates is another way. In my opinion often the best.
Another alternative is using blocks.
In my opinion Objective-C is very structured, and I prefer it a lot over C#.

Related

VB.Net, specify a thread for BackgroundWorker to use?

This is far-fetched I know but I have to ask. Is there a way to specify the thread that a BackgroundWorker instance is to use? Or at least some way to force it onto another specific thread (whose reference I have). I have a large project that makes use of BackgroundWorker, and I have just recently started using some in-house FRAMEWORK (I have to) that uses Thread instead, and the two seem not be happy with each other (I know the reason but I can not fix it as it is in the framework whose guts I can modify) that is why I ask this question, before I spend days converting my project to use FRAMEWORKS Threading functions.
You might be able to derive from the BackgroundWorker class as it's not sealed and override the methods for RunWorkerAsync etc. Would be painful and easy to introduce bugs, but that would give you the ability to kick off the DoWork event onto your in house thread framework.

DataSource pattern versus setting Properties while Configuring Objects

I often get confused with when to use DataSource Pattern and when to use the Properties for providing configuration information to objects.
I have two ways to do this,
Generally I keep a lot of properties in the Object's class that has to be configured and a method that resets the object and continues with the new properties.
And the for the Object which is configuring the other object, I keep a method that with the name configureXYZ:WithValues: , which resets the properties and calls the reset method of the object to be configured.
This I have seen with MPMoviePlayerController, that we have to set properties.
and Other way is how tableView works, all the configuration information comes from datasource methods.
Can anyone throw more light on which way is preferred in which scenario.
Because Its often I feel tempted to use design patterns and make the code look stylish but I wanted to know when do we actually need these.
I am absolutely clear with delegate pattern and have to use it on regular basis.
DataSource was one thing I was never clear with.
When designing a class, the key factor you should consider when deciding between using a delegate or properties is how often the values can change. Properties work best if you will set the values one time and they should never change again. Delegates (of which datasource is just an example) work best if the values might change over time or change due to conditions.
For example, in UITableView, the number of rows is highly dynamic. It could change for many reasons outside of the control of the table view. What the rows even represent is highly dynamic. They might be data; they might be menu options; they might be pieces in a game. UITableView doesn't try to guess or control any of that. It moves it to a delegate (datasource) where potentially very complex decisions could be made.
MPMoviePlayerController has a few controls that mean very specific things and should almost never change (particularly once the movie starts playing). Basically you set the thing up, hit play and walk away. In that case, a delegate would likely be overkill.
There are many cases that are in the middle, and either way may be ok. I would encourage developers to consider delegation first, and then if it doesn't make sense go with properties. This isn't because delegation is always the right answer, but more because most C++- or Java-educated developers don't think in terms of delegation, so should make a conscious effort to do so.
Some other thoughts along these lines:
When using properties, it is ideal if they are configured at initialization time and are thereafter immutable. This solves a great number of problems.
If you find yourself needing a lot of properties, delegation is probably better and often simpler.
Delegate notification methods (somethingDidHappen:) are often better implemented as blocks. (Blocks are relatively new in ObjC. Many delegate-based Apple interfaces are moving to blocks, but you'll see a real mix out there for historical reasons.)
The difference between "delegate" and "datasource" is that a delegate manages behavior, while a datasource provides data. They are typically implemented identically.
It mostly depends on the dynamics of the class. UITableView is a very dynamic interface element. Its data comes and go. You can add/remove/edit/sort. You can interact with it. IF you assign properties to a tableView, it loses some of the properties that makes it as robust as it is. MPMoviePlayerController, on the other hand, has a different purpose. I have never used this class but by the looks of it, it reads one video file and provides playback. There is not many changes to it, so properties makes a lot of sense.
If you are writing a class, and you need that class to be as flexible as possible(UIPickerView, UITableView), having delegates allows you to do so. If your class only works with limited configuration after initialization, you could be better by taking the property approach.

Designing Cocoa application

I am writing a Cocoa application that I keep adding buttons, views, and layers to. However, because of all these additions my appdelegate class has become rather big and difficult to read. I therefore decided to move some of the UI related calls to other classes from the appdelegate. However, it seems UI calls have to be done only on the main thread, and (correct me if I am wrong) from the appdelegate. My experiment to move calls into other classes also made me run into difficulties on making sure everything was performed correctly on the main thread. So, all of my UI calls are still called from the appdelegate class.
My questions is how can I improve the design of my application? Can I call the UI from other classes than the appdelegate in a way that avoids problems with threading? Can I split the appdelegate class into severeal files, one for buttons, one for views etc., or is there a better way to design the application? Any suggestions on links to examples or tutorials/books are greatly appreciated.
Thanks everyone. Cheers, Trond
Cocoa is based heavily on the Model-View-Controller architecture. There is some really great reading on how to use this pattern in Cocoa in the Cocoa Design Patterns reference. Basically, you want to have as little UI code in the app delegate as possible. The app delegate should be responsible only for app-level control, if possible. It's much better to put UI controller code in separate controller classes. The MVC architecture leads you down the right path; Cocoa provides the views, you write your model classes—the "business" logic of your app—and then use a view controller to coordinate the two.
UI calls need to be done from the main thread, that part is correct. However, you don't need to do them from the app delegate. You can do them everywhere you like, as long as it's done on the main thread.
Now, some UI things can be done on other threads but AFAIK UIKit is not designed to be thread-safe and thus strange things and crashes may occur.
There's nothing wrong with splitting things off into other specialized classes. I do it all the time. You might want to introduce a single object that stores and manages states and maybe gives access to your specialized "controllers".
Have a look at UIViewController and what it offers you, if you can split your app into "pages" this might be the way to go.

Decorator Pattern For UITableViewCell

I was wondering if anyone has ever attempted to or thought of using the decorator pattern to make it easier to DRY up UITableView code.
What I'm thinking of is creating a set of reusable decorators for UITableViewCells, for instance one for adding background gradients, one for adding different shadings, and a variety of other stylings.
You would then be able to chain the decorators together, to get the desired effect, instead of having to bolt on some Frankenstein code to different objects every time you wanted to reuse similar design styles.
Does this make sense, or am I just recreating the wheel? I really dislike subclassing UITableViewCells, and think this would be a good way to get around that problem.
I'd love to hear the opinion of some of you guys who have way more Objective-C and UIKit experience than I do on this topic.
Isn't the decorator pattern typically based around an abstract base or interface/protocol at the root? Since your base here isn't exchangeable (it must be a UITableViewCell) this could be tricky.
Maybe you can pull it off by proxying, i.e. subclassing NSProxy to wrap a UITableViewCell. I don't know if that will work, as UIKit classes tend to be quite tightly integrated with one another. The proxy and the the real cell will have different identities, and if the cell sends messages to the table view with self as an argument, this could confuse the table view.
Another option is to subclass the table view cell once to add some kind of extensible delegate mechanism whereby you can dynamicall add delegates to each cell. I'm calling them delegates as they won't subclass from the table cell, just add a behaviour for it. You would then intercept messages to the cell and decide dynamically, based on the delegates present in the object, whether a delegate receives the message or whether it goes directly to the superclass (UITableViewCell) method implementation. You could define a protocol for each delegate which declares the new methods/properties the thusly extended cell will accept.
I don't know how much trouble this would be to implement in the first place, and how complicated the code for each delegate would be. I guess you'd have to try it to see if it's worth it in practice.
In any case, mixing in behaviours to UIKit classes would definitely be an interesting and useful thing to have. For my own apps, I've built an automatic view layouting system which lays out views depending on their content, the available space and certain resizing parameters. Something like this would probably reduce the amount of repeated code in that system somewhat.
While this approach is sound from an architectural point of view, in the reality of iOS it has a terrible effect on performance (it has been attempted before and did not end well). iOS caches pre-rendered bits of tableview cells as much as possible, so performing runtime modifications of the layout and appearance of different cells in a way that the designers of the UIKit did not anticipate would destroy that caching, and performance would suffer.
Take a look at how Matt Gallagher handles custom cell drawing, his approach has been pseudo-blessed by Apple at WWDC this year. Also, watch the "Tips and tricks to improve responsiveness" and "Understanding UIKit rendering" sessions from WWDC, as they address real world techniques for improving performance of UITableView.

First Responder Explanation Needed

I asked a question earlier on here regarding the use of First Responder - and got a response here:
Trouble with First Responder
Would anyone mind giving me a 'dummies' version of this? Being new to Cocoa, I don't really know where to start with either one of these methods. I award answers quickly
Zach
First Responder is specifically this.
What you're asking about, though, is target-action. You have a UI object (button, menu item) that you need to cause multiple things to happen, but the UI object only sends one action.
Hence the solution: Make that action do multiple things.
Hook the UI object up to an action method you implement in your controller object (in your case, the document). In that method, do all the things the button needs to cause.
The subclassing solution is basically the same thing, except instead of hooking the UI object up to your document, you hook it up to the font manager, but you also make the font manager an instance of a subclass of NSFontManager that you create, rather than an instance of NSFontManager directly. In your subclass, you override addFontTrait: and add the other behavior in your implementation. At either the start or the end of that method, you send [super addFontTrait:sender] to invoke NSFontManager's implementation, so the original implementation gets done.
Long paragraph, but it's not actually all that much more work: The difference is just making the subclass and making the instance an instance of that subclass.
You've said before that “the Apple Documentation is incredibly vague”, but it's really not. There just happens to be a lot of it, and maybe you haven't been looking at the right documents.
These are the documents you need to read, from start to finish, and in order:
EDIT: This list is for Xcode 3. I posted an updated (for Xcode 4) version of this list in another answer.
The Objective-C Programming Language
The Memory Management Programming Guide for Cocoa
The Cocoa Fundamentals Guide (which explains target-action, among other things)
Application Architecture Overview
Resource Programming Guide
Interface Builder User Guide
The Xcode 3 guides:
Xcode Project Management Guide
Xcode Workspace Guide
Xcode Build System Guide
Xcode Debugging Guide
Document-Based Applications Overview
There is also an Instruments User Guide, but, unfortunately, that one is vague—or, to be more precise, incomplete. It omits a lot of useful information, like how to use Instruments' Zombies template to debug crashes. It's a high-level overview, nothing more.
Also, bookmark these:
Cocoa Core Competencies, a quick reference to all the concepts you need to use
The Foundation Framework Reference
The AppKit Framework Reference
The Core Foundation Framework Reference
The Core Graphics Framework Reference
That's a lot of reading, but it'll tell you everything you need to know, and that order is roughly the order you'll need to know it in.
The other answer says that you have two options:
First: Do replace the action by the one created by you and then implement the feature of the original version yourself. In this case, it suffices to just call the appropriate method of NSFontManager. That is, you add the original functionality to your own implementation of the method. This way, both actions are executed.
Second: Subclass the class where the original functionality is implemented and add your implementation by overriding the method that is called -addFontTrait. This way, your code gets executed "alongside". This question might help you to find the correct implementation.
So, the essence is that you can either add the original functionality to your implementation or the other way around. In this case, I would try the first one.