How to wrap class properties? - objective-c

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.

Related

What's the correct practice to add common properties to multiple classes?

Suppose I have one table view controller (controlling a static table view) and another regular view controller.
I want to add a common property to both of them. The first thing came in my mind is subclassing, meaning let these two controllers derive from a common abstract super class. After pondering a bit, I recall protocol can also achieve this.
My questions is, which approach will be the correct practice, or there are better practices?
Subclassing is likely the correct approach. Protocols don't add properties automatically, they only dictate that if your class conforms to a specific one that the class implements them. If your coming from the Java world then an interface would be the equivalent.
A category might be appropriate if you want to add common functionality (methods) to all instance of a class, such as a UITableview controller. The downside is that you can't declare additional instance variables (or properties) via a category (well technically you can via associated objects, but that's another rabbit hole).

Forward all messages to other object

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.

What are the key reasons for using #protocols in Objective C? [duplicate]

This question already has answers here:
What is a Protocol?
(2 answers)
Closed 10 years ago.
Why would I want to use a protocol rather than create a subclass and inherit the methods..?
Please explain it to me, i'm to confused about this topic, i'm not very pleased with the explanation in the book im reading.
Where do I use protocols instead of other ways to get the methods..? if I can subclass a class and get the methods why would i want to use a protocol where i need to define the methods?
Why would I want to use a protocol rather than create a subclass and
inherit the methods..?
Protocols make it possible for unrelated classes to all implement the same interface. Instances of each of those classes can then be used by a client of the protocol. For example, UITableViewDataSource is a protocol that provides an interface by which a table can ask for data from any object that implements the protocol. The table view doesn't care what the type of the object is so long as it implements the data source interface.
Imagine how unpleasant things would be if all table data sources had to inherit from a common class! Objective-C only provides single inheritance, so you'd effectively be constrained to using only a single kind of object for your data source. With protocols, though, a data source can be a view controller, a model object, or perhaps even a remote object.
To be more specific, protocols allow a form of polymorphism. That means that a single object can take several forms: e.g. view controller, table data source, table delegate, scroll view delegate. Because Objective-C is a single-inheritance language, you only get one of those interfaces via inheritance. The rest you implement yourself, but that often makes sense because you generally adopt a given protocol in order to customize some other object's behavior anyway.
Because subclassing and protocols are two different things. Subclassing extends a class with new functionality while inheriting all previous functionality of a specific class while a protocol, when applied to a class, simply adds functionality to it and doesn't inherit anything from it; what that class is usually doesn't matter.
Protocols are most frequently used for the delegate pattern in Objective-C whereby an object can send a message to another object without caring WHAT that object is (i.e. it's class).
Often times, a delegate is declared as:
#property(nonatomic, assign) id < MyObjectDelegate > delegate;
Notice that the class of the property is id -- in essence, you don't care if the object is a car or a turtle -- all you need to know is that it is an object (id) and that it contractually subscribes to the functions you need it to. So if your delegate is type turtle, you can call [delegate myStateChanged]; or, if your delegate is a car, you can call [delegate myStateChanged]. All you need to know is that, if you send a message to it, it will accept it.
I would look up and read about the use of Objective-C delegates as I think it will really help you understand protocols better and how it's different than subclassing. I don't know if you're familiar with other, object-oriented programming languages, but if so, protocols are most similar to Interfaces in other languages.
Protocols are useful because you can implement many protocols, instead you can only extend a single class.

Better way to share a set of methods between two classes besides a category on NSObject?

Specifically, I would like to share a set of utility methods between NSTreeNode and my class which is not a subclass of NSTreeNode. My class (WCTreeNode) inherits from WCObject, which is a subclass of NSObject.
My current solution is to have the methods declared in the header of my class (WCTreeNode) and then again in a category on NSTreeNode. However, I'm not particularly fond of this because whenever I make changes, I have to make sure to do it in both files.
I realize I could just make a category on NSObject and list the methods there, but that doesn't seem specific enough to me and doesn't let the compiler help me as much with respect to type-checking.
I'd really like a solution that allows me to keep the code in a single file so I don't have to change things in multiple places each time.
Any suggestions?
Suggest creating a helper class which will be a delegate for all "dirty" routines in your classes. Make its instance a property of your classes and use it when you need.
I think a protocol is the way to go here. Put your custom methods in a protocol, and subclass NSTreeNode; the only customization this subclass would make would be to adopt the protocol. WCTreeNode can also adopt the protocol. This allows type-checking and keeps the methods in one place.

When to use Categories

I've recently discovered categories and was wondering when it might be appropriate to use them in a user defined class/new class. For example, I can see the benefits of adding a category to an existing class like NSString, but when creating a new class what would be the advantage of adding a category to this rather than just implementing a normal method?
Hope this makes sense.
Many thanks
Jules
The answer isn't really any different for your own classes than it is for framework classes. If you have multiple projects, you'll likely end up sharing some classes between them. However, you may want to extend some of your classes so that they work more easily with a specific project, but not want to include those extra methods in your other projects, where they might not make sense. You can use a category to extend your class without needing to subclass.
If I understand your question correctly, creating a "new class" is always "subclassing" because you're subclassing NSObject at the very least.
You could use categories on a new class to separate out sections of responsibility of a complex class. For example, all the basic functionality (instance variables, accessors, description, etc.) can go in one file (the "main" class file) while all methods to support a protocol (such as NSTableViewDataSource) can go in another.
Some take this approach to keep things "neat". I'm a firm believer in "if it's my own custom class, all its code should be in one file" so I do not personally do this. I demarcate different logical aspects of the class' code with "#pragma mark Some Section Name" to help navigation and readability. Your mileage may vary.
Adding a Category on NSString is useful when you want to call a method on every single NSString instance you will encounter. This is a real improvement over inheritance for this kind of object because they are used by the core framework and you don't have to convert a NSString object to your subclass when you want to call your custom method.
On the other hand, you can just put methods in, no instance variables.
In the book Refactoring by Martin Fowler, he has a section titled "Introduce Foreign Method" (A server class you are using needs an additional method, but you can't modify the class.) That's what categories are good for.
That said, there are times when using a category, instead of changing the class, is appropriate. A good example on using a category, even though you could change the server class, is how Apple handled the UIViewController MediaPlayer Additions. They could have put these two methods in UIViewController itself but since the only people who would ever use them are people who are using the Media Player framework, it made more sense to keep the methods there.