Forward all messages to other object - objective-c

I have next issue:
I have a decorator for the NSButtonCell class, which adds some functionality. As it is a decorator - is's a subclass of NSButtonCell. I didn't like to create subclasses, because the same functionality must be dynamically added\removed to some other subclasses of NSButtonCell. And, as it is a decorator, I must forward all messages to the decorated object, because some subclass can have own 'setting', behaviour and etc. Because NSButtonCell has many methods, I can't write code to redirect all messages to decorated object. Please, tell me, how I can redirect all received messages to decorated object?

Round Peg meet Square Hole.
The reason why you are finding it so hard to do this is because it is an exceedingly non-standard pattern to use for implementing UI. Method forwarding as implemented by either forwardInvocation: or NSProxy is useful, but pretty much never used to implement the Decorator pattern in the context of the UI.
While you could use a subclass of NSProxy that selective forwards or implements the methods you need, that is a complete waste of code compared to simply creating a subclass.
Just use a subclass and be done with it.
However, only subclass if you really need to. If the provided NSButtonCell can do all that you need and it is merely a matter of configuring it, then configure it in your controller or in whatever mechanism that you use to layout and present your user interface.
And in your case, it sounds like a central controller or UI configurator is the way to go as that will centralize the functionality into a single spot that can then control multiple (potentially minimal subclasses) instances of the various UI classes.

Using NSProxy is the standard approach for creating objects that act as stand-ins for other objects or objects that don’t exist yet. Its entire structure is based around handling methods and forwarding them to the true object.

Related

How to wrap class properties?

there is a conceptional question:
I want to have a wrapper class which forwarding all called selectors to a given object. How do I do this?
And here is why:
I have a library for synchronizing data with a service. And I use Core Data.
For the library I have to create classes of a specific protocol. But I can not use the same protocol for the Core Data subclasses.
My idea is to create a subclass of the specific protocol and forwarding the protocol calls to the Core Data Object.
But there are many subclasses and many properties per subclass and without changing the Core Data subclasses (project specific requirement!)
Is there a way to do this without overwriting every method?
Thanks for your time =)
Implement -forwardingTargetForSelector:. You can return another object to forward unknown messages to. If that is most of what your class will do, you may want to just subclass from NSProxy rather than NSObject. (NSProxy has the advantage that it doesn't implement all of the standard NSObject methods, so you can forward those as well.)
One common problem with this approach is that the compiler will complain that your class does not respond to the selectors you're sending it. The usual way to address this is by requiring that users of your object declare it as id. This can often be inconvenient as well, so this is a bit of a last resort if other approaches are not possible.
But usually the better approach is to make your class a subclass of the target and add the additional methods required for your protocol. Or you can add the additional methods to the Core Data class via a category.
The answer to your specific question is yes. Message Forwarding contains everything you need.
I think you might want to step back and evaluate other options. For example, can you add this functionality to a base class instead of a proxy class.

Standard delegate pattern seems at odds with delegate purpose

If I follow any of a number of examples available on the web, I see a common theme emerge with the delegate pattern:
myClass.delegate = self;
From what I read, delegation is supposed to uncouple behavior, but allow interaction between classes, however, only assigning a single delegate seems to be 100% at odds with this behavior.
I have a web dev background, and I am intimately familiar with pub/sub patterns, but what I'm trying to wrap my head around is why I would only allow a single delegate (self) to be able to act on whatever happens in myClass. That would seem to ruin the entire point of delegation.
Maybe I'm misunderstanding something, or maybe this is only the simplest form of delegation, but could someone please explain how statically assigning (in the classic sense) one class to another's delegate decouples behavior in any meaningful way.
Bonus: Perhaps a way to allow multiple classes to act on a delegation.
The delegate asserts additional control over the delegated class. The most simple example is windowShouldClose: method in the NSWindowDelegate protocol. The class delegate gets a chance to proactively override closing the window in NSWindow. If multiple delegates were allowed, multiple delegates could supply conflicting orders which would be an undesirable result.
Delegation allows you to customize behavior without subclassing. Because a class can implement many delegate protocols, it is a key part of the MVC programming model in Objective-C. Delegation allows you to create one class as a "Controller" of multiple other classes.
For acting reactively to what happens to the class, you use a pub/sub model of key value observing. For example, NSOperationQueue has an observable property operationCount to let you react to changes in the number of operations in the queue.
It decouples behavior in the sense that the delegator needn't know anything at all about the delegate other than that it (possibly) responds to a certain set of methods. This makes it so that classes that have delegate can be used in entirely different codebases/situation without changes. It's particularly applicable when writing Framework classes that will be used by someone else, which is one reason you see it so much in the system frameworks.
One of the major uses of delegation is to allow customization of an object's behavior without subclassing. Take for example the NSWindowDelegate method -windowWillResize:toSize:, where the delegate can return a different size than the suggested one to implement custom sizing behavior. How would this scenario be handled with multiple delegates each returning a different value?
Of course, sometimes delegate methods are merely meant to inform the delegate that some particular event has occurred. In these cases, it is indeed reasonable for multiple objects to want to be notified. This is provided for in Objective-C/Cocoa by notifications (NSNotification), and Key Value Observing (KVO). You'll find plenty of cases in Cocoa where a delegate method also has a corresponding notification posted in case objects other than the delegate want to know about it (e.g. windowWillClose:/NSWindowWillCloseNotification).

When to use (or not use) a delegate

This is a pretty general question, but I was wondering today about delegates. At this point I don't really have a specific time I do use them or don't use them - aside from obvious cases, like passing selections from a picker or tableview stuff. For example, if there's a situation where I can pass a reference to an object around and use that to call methods, is there a reason to implement a delegate? In summary, what is the delegate pattern intended for use in and when is it better to NOT use it?
Thanks for the quick and comprehensive answers! They were all extremely helpful.
The advantage of the delegate pattern is loose coupling between the delegating object and its delegate. Loose coupling improves a class's reusability in other contexts.
The delegating object doesn't have to know anything about the object it communicates with (aside from the requirement that it implement the delegate protocol) – especially not its class or what methods it has. If you later want to reuse your component in a different context or have it communicate with another object of a different class, all this object has to do is implement the delegate protocol. The delegating object does not have to be changed at all.
There is also a downside to this, of course, and that is that a bit more code is required and the code you write is not as explicit and therefore may be a bit harder to understand. Whether this (generally small) tradeoff is worth it depends on your use case. If the two objects are tightly coupled anyway and the probability of reuse in the future is low, using the delegate pattern might be overkill.
See this discussion
A delegate allows one object to send messages to another object when an event happens.
Pros
Very strict syntax. All events to be heard are clearly defined in
the delegate protocol.
Compile time Warnings / Errors if a method is not implemented as it should be by a delegate.
Protocol defined within the scope of the controller only.
Very traceable, and easy to identify flow of control within an application.
Ability to have multiple protocols defined one controller, each with different delegates.
No third party object required to maintain / monitor the communication process.
Ability to receive a returned value from a called protocol method. This means that a delegate can help provide information back
to a controller.
Cons
Many lines of code required to define: 1. the protocol definition, 2. the delegate property in the controller, and 3. the implementation of the delegate method definitions within the delegate itself.
Need to be careful to correctly set delegates to nil on object deallocation, failure to do so can cause memory crashes by calling methods on deallocated objects.
Although possible, it can be difficult and the pattern does not really lend itself to have multiple delegates of the same protocol in a controller (telling multiple objects about the same event)
The "use case" for delegation is pretty much the same as for inheritance, namely extending a class behavior in a polymorphic way.
This is how the wikipedia defines delegation:
In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.
There are, obviously, many differences between delegation and inheritance, but the biggest one is, IMO, that inheritance is a fixed (aka, compile-time) relationship between two classes, while delegation can be defined at run-time (in languages that support this). On the other hand, inheritance offers better support for polymorphism.
Delegation is a huge topic (as inheritance is), and you can read a lot about it. In the end, deciding whether using delegation or inheritance comes down to deciding whether you want an "is-a" or and "has-a" relationship, so it is not so easy to list guidelines for choosing that.
For me, basically, the decision to create a delegate comes from the observation that:
my code presents a set of homogeneous behaviors (homogeneous here means that can be recognized as having a common "nature");
those behaviors might be be "customized" for particular cases (like in, replaced by alternative behaviors).
This is my personal view and a description of the way I get to identify "delegation" patterns. It has probably much to do with the fact that my programming discipline is strongly informed by the principle of refactoring.
Really, IMO, delegation is a way to define "customization" points for your class. As an example, if you have some kind of abstract workflow, where at each step you take some action depending on certain condition; and furthermore those concrete actions could be replaced by other of another kind, then I see there the chance of reuse through delegation.
Hope this helps.

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?
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?
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.

Choosing a Singleton or a Category?

Fairly early on in my app, when I was a lot less experienced than I am now, I wanted to spice up some transitions between view controllers with my own custom animations. Having no idea where to start, I looked around SO for a pattern like MVC that could be accessed from nearly any controller at any time, and as it turns out, a singleton was the way to go.
What I didn't realize is that there seems to be a strong and well-defended hatred of the singleton pattern, and I myself am starting to see why, but that is beside the point.
So, a while later, I decided to move my very same implementation into a category on UINavigationController (after all, it handles transitions!), kept the original classes around for comparison, and am wondering which method would work best. Having thoroughly tested both implementations, I can say without a doubt that they are equal in every way, including speed, accuracy, smoothness, frame-rate, memory usage, etc. so which one is 'better' in the sense of overall maintainability?
EDIT: after reading the well-written arguments you all have made, I have decided to use a singleton. #JustinXXVII has made the most convincing argument (IMHO), although I consider every answer here equally worthy of merit. Thank you all for your opinions, I have upvoted all answers in the question.
I believe the best option is use the category.
Because if you are already using UINavigationController, do not make sense create a new class that will only manage the transition, like you told: (after all, it handles transitions!)
This will be a better option to maintain your code, and you will be sure that the thing do what they expect to do, and if you already have an instance that do the transitions, why create another?
The design patterns, like singleton, factory, and others, need to be used with responsibility. In your case, I do not see why use a singleton, you use it only to no instantiate new objects, you do not really need to have only one instance of it, but you do it because you want only one.
I'll make the case for a singleton object. Singletons are used all over UIKit and iOS. One thing you can't do with categories is add instance variables. There are two things about this:
MVC workflows don't tolerate objects with intimate knowledge of other objects
Sometimes you just need a place to reference an object that doesn't really belong anywhere else
These things go against each other, but the added ability to be able to keep an instance variable that doesn't really have an "owner" is why I favor the singleton.
I usually have one singleton class in all of my XCode projects, which is used to store "global" objects and do mundane things that I don't want to burden my AppDelegate with.
An example would be serializing/archiving objects and unarchiving/restoring. I have to use the same method throughout several classes, I don't want to extend UIViewController with some serializing method to write and read arbitrary files. Maybe it's just my personal preference.
I also might need a quick way to lookup information in NSUserDefaults but not want to always be writing [[NSUserDefaults standardUserDefaults]stringForKey:#"blah"], so I will just declare a method in my singleton that takes a string argument.
Until now i've not really thought too much about using a category for these things. One thing is sure though, I'd rather not be instantiating a new object a hundred times to do the same task when I can have just one living object that sticks around and will take care of stuff for me. (Without burdening the AppDelegate)
I think that the real question is in "design" (as you said, both codes work fine), and by writing down your problem in simple sentences, you will find your answer :
singleton's purpose is to have only one instance of a class running in your app. So you can share things between objects. (one available to many objects)
category purpose is to extend the methods available to a class. (available to one class of objects only ! ok...objects from subclasses too)
what you really want is to make a new transition available to UINavigationController class. UINavigationController, which has already some method available to change view (present modal views, addsubviews, etc.) is built to manage views with transitions (you said it yourself, it handles transitions), all you want to do is adding another way of handling transitions for your navigation controllers thus you would preferably use a category.
My opinion is that what you want to achieve is covered by the category and by doing this you ensure that the only objects which are accessing this method are entitled to use it. With the singleton pattern, any object of any class could call your singleton and its methods (and... it could work nobody knowing how for an OS version n but your app could be broken in n+1 version).
In this implementation, for which there is no need to use a Singleton, there may be no difference at all. That doesn't mean that there isn't one.
A plastic bucket holds as much water as a metal bucket does, and it does it just as well. In that aspect there seems to be no difference between the two. However, if you try to transport something extremely hot, the plastic bucket might not do the job so well..
What I'm trying to say is, they both serve their purposes but in your case there seemed to be no difference because the task was too generic. You wanted a method that was available from multiple classes, and both solutions can do that.
In your case, however, it might be a whole of a lot simpler to use a Category. The implementation is easier and you (possibly) need less code.
But if you were to create a data manager that holds an array of objects that you ONLY want available at one place, a Category will not be up to the task. That's a typical Singleton task.
Singeltons are single-instance objects (and if made static, available from nearly everywhere). Categories are extensions to your existing classes and limited to the class it extends.
To answer your question; choose a Category.
*A subclass might also work, but has its own pros and cons
Why don't you simply create a base UIViewController subclass and extend all of your view controllers from this object? A category doesn't make sense for this purpose.
Singletons, as the name suggests, has to be used when there is a need to be exactly one object in your application. The pattern for the accessor method ensures only this requirement being a class method:
+ (MyClass*) sharedInstance
{
static MyClass *instance = nil;
if (instance == nil) instance = [[MyClass alloc] init];
return instance;
}
If implemented well, the class also ensures that its constructor is private thus nobody else can instantiate the class but the accessor method: this ensures that at any time at most one instance of the class exists. The best example of such class is UIApplication since at any time there might be only one object of this class.
The point here is that this is the only requirement towards singleton. The role of the accessor method is to ensure that there is only one instance, and not that it would provide access to that instance from everywhere. It is only a side effect of the pattern that, the accessor method being static, everybody can access this single object without having a reference (pointer) to it a priori. Unfortunately this fact is widely abused by Objective C programmers and this leads to messed up design and the hatred towards singleton pattern you mentioned. But all in all it is not the fault the singleton patter but the misuse of their accessor method.
Now turning back to your question: if you don't need static / global variables in your custom transition code (I guess you don't) then the answer is definitely go for categories. In C++ you would subclass from some parent BaseTransition class and implement your actual drawing methods. Objective C has categories (that in my opinion is another way that easily messes up the design, but they are much more convenient) where you can add custom functionality even accessing the variables of your host class. Use them whenever you can redeem singletons with them and don't use singletons when the main requirement towards your class is not that it would be only one instance of it.