What use cases are there for defining a new root class? - objective-c

We know that in Objective-C there are two main root classes: NSObject and NSProxy. There are other roots (mainly for private and legacy purposes) like Object, and NSLeafProxy.
Defining a new root is fairly trivial:
#interface DDRoot <NSObject>
#end
#implementation DDRoot
//implement the methods required by <NSObject>
#end
My question is: why would you ever want to define a new root class? Is there some use-case where it's necessary?

There are two primary reasons to create a new root class; proxying & a new object model.
When proxying, it can be useful to implement a new root class such that you can basically handle any and all of the class/object's behaviors in a custom fashion. See NSProxy.
The Objective-C runtime is flexible enough that you can support a new object model quite easily (where easily discounts the inherent complexity of creating such a beast in the first place). Actually, many of the behaviors that are considered inherent to the runtime -- KVC, KVO, etc.. -- are implemented as a part of the NSObject class itself.
I know of at least one company that -- as of about 8 years ago, at least -- had implemented their own object model as a part of building their ~500k LOC financial analysis engine.
The key, though, is that if you go this route, you don't try to make your classes interact with Foundation/CF/AppKit/UIKit, etc. If you need that, just subclass NSObject already!
It is interesting to note that NSManagedObject is effectively a root class in that it does some pretty seriously custom stuff, but it is a subclass of NSObject so subclasses of NSManagedObject are inter-operable with the rest of the system.

As far as I can tell, there should be no reason for creating your own root class, because short of implementing all of the NSObject protocol methods yourself, you're going to be missing out on a lot of functionality, and going to be making a lot of calls to the Objective-C runtime that should essentially be done for you.
Unless you really had to implement the protocol differently from the default (NSProxy is a special case that does have to), you shouldn't need to make your own root class. I mean, you'd have to be writing a class that cannot fundamentally be represented by NSObject and the protocol as implemented by Apple, and in that case, why are you even writing it in Objective-C?
That's what I think. Maybe someone can come up for a creative use for it.
(People researching the topic should go look at the NSObject Class Reference, NSObject Protocol Reference, 'Core Competencies: Root Class' document, and the 'Root Class' section of the Fundamentals Guide: Cocoa Objects document.)

Objective-C and Cocoa are separate things, and in principle it’s possible to define entirely new application frameworks that don’t use Foundation. The financial analysis people bbum mentioned are a practical example, and I believe they’re still around.
Another use is to make a proxy that’s more minimal than NSProxy, as Mike Ash does here.
Oh, and the private NSInvocationBuilder is a root class, presumably for the same reasons as Mike’s proxy. Capturing invocations for later use is something one might want to recreate.

Companies like the OmniGroup have defined a version of NSObject to use as their own base class for everything.
It's essentially a subclass of NSObject with some debug stuff. Other than that, it's usually a terrible idea to fight the framework.
Find Omni's code here:
https://github.com/omnigroup/OmniGroup

Related

What are the advantages and disadvantages of using Protocol vs Inheritance? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In objective-c?
I had a class made and then I decided that I want another class that's like the first class. Should I use protocol and ensure that both classes support that protocol or should I create a parent class and decide that the 2 classes inherit from that one class?
Note:
The classes are: Business, Catalog, AddressAnnotation (currently works only on business only) and AddressAnnotationView (currently works only on business only). I want the same thing to work on Catalog. There is also BGGoogleMapCacheForAllAnnotations that manage when the annotations are clumped together (which now should be able to handle both AddressAnnotation for Catalog and Business. Also there is BGGoogleMap View Controller that I want to turn into a parent class.
If you use a protocol, then you have to define methods shared by both class types twice. Protocols are generally reserved for specific patterns, such as the delegation pattern, to add security and make it harder for you to make a mistake, or when several classes already embedded in a class hierarchy need to share common methods and have this sharing be documented in some way. If one class can be represented as a more specialized version of another, you should inherit.
For instance, let's say you you have a Vehicle class in your game that knows how to do all sorts of stuff, such as move around. If you wanted to make a Car class, you'd probably subclass the Vehicle class so that you could inherit all of its method implementations; either to utilize them wholesale or implement your own version of the methods, probably performing some task specific to the subclass before calling the superclass's implementation as well. Subclassing is for when you want to inherit the traits and behaviors of your superclass while modifying it in some way. This is especially true when additional data must be added to the class, such as instance variables, because you can't do that with categories (although you can with a Class Extension, often seen as a sort of private interface). Generally, subclasses have more specialized purposes than their superclasses as a result.
Protocols are just that, protocols. They're there to prevent you from screwing up or forgetting something, and ensure that every object does what it's supposed to, triggering compiler warnings when classes aren't behaving like they are supposed to. This is important for patterns such as delegation, since it's the only way to ensure that the delegate implements the methods you need beyond breaking encapsulation and knowing what type of object your delegate is. For instance, look at the the code below, from one of my projects.
//SGSprite.h
#protocol SGSpriteDelegate
- (BOOL) animation:(int)animationIndex willCompleteFrameNumber:(int)frame forSprite:(id)sender;
#end
#interface SGSprite : NSObject
#property (nonatomic, assign) id<SGSpriteDelegate> delegate;
#end
//SGViewController.h
#interface SGViewController : UIViewController <SGSpriteDelegate>
//...dreadfully boring stuff
#end
Many classes utilize my SGSprite class for rendering textured 2D quads. Sometimes, they need to know when a sprite reaches a certain frame of animation, so SGSprite instances need to call a method on their delegates to let them know when certain frames are reached. The only way to ensure that delegates to instances of this class implement this method, and, indeed, warn me if someone tries to assign an object that doesn't as a delegate, is through the use of a protocol. You'll notice that if I simply make the delegate a plain id I'll get a warning whenever I call this method on my delegate, since its implementation cannot be found, while if I import the delegate's header/statically type the delegate, the class is no longer well encapsulated.
You don't technically need protocols in most cases; you could define all of the methods without a protocol in all of the classes that would ordinarily adhere to said protocol, and everything would work fine. However, these common methods are no longer documented. Thus, beyond the security of knowing certain classes or anonymous objects implement methods you need them to implement, you can also quickly tell what does what and how. Protocols are for when you need to ensure that a class, or instance of a class, implements some method, especially when an object's type shouldn't be known to keep a class encapsulated.
There are a lot of factors that could influence that decision. For one, when you say that the other class is "like the first class", what does that mean? Does it mean that they'll do 90% of the same things in exactly the same way? Does it mean that they'll do a lot of the same kinds of things, but each in a slightly different way?
If many of the existing methods in the first class will work as-is or with little modification in the second class, subclassing lets you get all of those methods "for free" so you can just focus on the differences. If you would need to rewrite most of the code, however, and just want to define the two classes as performing similar actions then a protocol might make more sense.
I've personally used subclassing exclusively, primarily because I haven't run into a situation where a protocol made sense to me in my code - of course, after a while it's more out of habit than conscious decision. When I began converting my app to using Core Data, subclassing fit in very nicely because Core Data offers the ability to create subentities with inherited attributes and relationships. That made it easier to grasp conceptually.
If you think about your current code, you're already subclassing (NSObject, view controllers, etc.) and possibly using protocols (NSCoding, view delegates, etc.). Think about how you use those existing classes and protocols and how those use cases would apply to your own classes.

How safe are Objective-C categories?

Objective-C categories are extremely useful, but there are some problems with this power. These come in basically two forms which I know of:
Two categories attempting to add the same convenience method. In this case, it is undefined which one is used. If you are careful - not adding too many methods or using particularly common method names - the first problem should almost never be an issue.
New methods being added to a class by a writer that clash with a category. In this case the category overrides the class method. Since the class may not be under my control, I am more worried about this problem.
Backporting changes should be fairly safe, but implementing interfaces or adding convenience methods seem more dangerous. I know that Cocoa seems to use it for convenience methods quite a lot, but then again the base class is under there control. I think maybe they are just using the categories to reduce dependencies - so a String class can have convenience methods for working in Cocoa, but if you don't use Cocoa, it isn't pulled in.
So, how safe are categories/what guidelines are there for keeping them safe?
Usually, when extending code not under your control (e.g. Foundation), it's traditional to use a prefix or suffix on the method name to avoid these sorts of collisions.
Example from Peter Hosey's perform on main thread category:
#interface NSObject (PRHPerformOnMainThread)
- (id) performOnMainThread_PRH;
#end
It's not the most beautiful solution, but if you're worried about fragility it's a good idea.
I found the Google Objective-C Style Guide useful and it includes a convention to help avoid the collisions you mention.

Discover subclasses of a given class in Obj-C

Is there any way to discover at runtime which subclasses exist of a given class?
Edit: From the answers so far I think I need to clarify a bit more what I am trying to do. I am aware that this is not a common practice in Cocoa, and that it may come with some caveats.
I am writing a parser using the dynamic creation pattern. (See the book Cocoa Design Patterns by Buck and Yacktman, chapter 5.) Basically, the parser instance processes a stack, and instantiates objects that know how to perform certain calculations.
If I can get all the subclasses of the MYCommand class, I can, for example, provide the user with a list of available commands. Also, in the example from chapter 5, the parser has an substitution dictionary so operators like +, -, * and / can be used. (They are mapped to MYAddCommand, etc.) To me it seemed this information belonged in the MyCommand subclass, not the parser instance as it kinda defeats the idea of dynamic creation.
Not directly, no. You can however get a list of all classes registered with the runtime as well as query those classes for their direct superclass. Keep in mind that this doesn't allow you to find all ancestors for the class up the inheritance tree, just the immediate superclass.
You can use objc_getClassList() to get the list of Class objects registered with the runtime. Then you can loop over that array and call [NSObject superclass] on those Class objects to get their superclass' Class object. If for some reason your classes do not use NSObject as their root class, you can use class_getSuperclass() instead.
I should mention as well that you might be thinking about your application's design incorrectly if you feel it is necessary to do this kind of discovery. Most likely there is another, more conventional way to do what you are trying to accomplish that doesn't involve introspecting on the Objective-C runtime.
Rather than try to automatically register all the subclasses of MYCommand, why not split the problem in two?
First, provide API for registering a class, something like +[MYCommand registerClass:].
Then, create code in MYCommand that means any subclasses will automatically register themselves. Something like:
#implementation MYCommand
+ (void)load
{
[MYCommand registerClass:self];
}
#end
Marc and bbum hit it on the money. This is usually not a good idea.
However, we have code on our CocoaHeads wiki that does this: http://cocoaheads.byu.edu/wiki/getting-all-subclasses
Another approach was just published by Matt Gallagher on his blog.
There's code in my runtime browser project here that includes a -subclassNamesForClass: method. See the RuntimeReporter.[hm] files.

how to inherit from multiple class

Let's say i have a griffon object that needs to be part of the felidae and bird class.
How do i do it ?
I can only make it inherit from 1 class at a time...
This may help...
Multiple inheritance
There is no innate multiple inheritance (of course some see this as a benefit). To get around it you can create a compound class, i.e. a class with instance variables that are ids of other objects. Instances can specifically redirect messages to any combination of the objects they are compounded of. (It isn't that much of a hassle and you have direct control over the inheritance logistics.) [Of course, this is not `getting around the problem of not having multiple inheritance', but just modeling your world slightly different in such a way that you don't need multiple inheritance.]
Protocols address the absence of multiple inheritance (MI) to some extent: Technically, protocols are equivalent to MI for purely "abstract" classes (see the answer on `Protocols' below).
[How does Delegation fit in here? Delegation is extending a class' functionality in a way anticipated by the designer of that class, without the need for subclassing. One can, of course, be the delegate of several objects of different classes. ]
-Taken from http://burks.brighton.ac.uk/burks/language/objc/dekorte/0_old/intro.htm
Multiple Inheritance in Objective C is not supported. The reason for not supporting this mechanism might be the fact that it would have been too difficult to include in the language or the authors thought it is a bad programming and design decision. However, in various cases multiple inheritance proves to be helpful. Fortunately objective C does provide some workarounds for achieving multiple inheritance. Following are the options:
Option 1: Message Forwarding
Message Forwarding, as the name suggests, is a mechanism offered by Objective C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before crashing the objective c runtime provides a second chance for the program to pass the message to the proper object/class which actually responds to it. After tracing for the message till the top most superclass, the forwardInvocation message is called. By overriding this method, one can actually redirect the message to another class.
Example: If there is a class named Car which has a property named carInfo which provides the car’s make, model and year of manufacture, and the carInfo contains the data in NSString format, it would be very helpful if NSString class methods could be called upon the objects of Car class which actually inherits from NSObject.
- (id)forwardingTargetForSelector:(SEL)sel
{
if ([self.carInfo respondsToSelector:sel]) return self.carInfo;
return nil;
}
Source: iOS 4 Developer's cookbook - Erica Sadun
Option 2: Composition
Composition is a cocoa design pattern which involves referencing another object and calling its functionalities whenever required. Composition actually is a technique for a view to build itself based on several other views. So, in Cocoa terminology this is very similar to Subclassing.
#interface ClassA : NSObject {
}
-(void)methodA;
#end
#interface ClassB : NSObject {
}
-(void)methodB;
#end
#interface MyClass : NSObject {
ClassA *a;
ClassB *b;
}
-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;
-(void)methodA;
-(void)methodB;
#end
Source: Objective-C multiple inheritance
Option 3: Protocols
Protocols are classes which contains method to be implemented by other classes who implement the protocol. One class can implement as many as protocols and can implement the methods. However, with protocols only methods can be inherited and not the instance variables.
You can't, per se. But you can have references to as many other objects as you need and you can use multiple protocols.
You can dynamically create a class at runtime and choose the methods of each parent class to inherit. Have a look at the NeXT runtime's documentation here about dynamically creating classes. I did this once just for fun, but I didn't get very far as it gets incredibly messy very quickly.
Edit
It gets more difficult though, because there can only be one superclass, otherwise the keyword super becomes ambiguous.
First, make felidae a subclass of bird. Piece of cake. :-)

What is the difference between inheritance and Categories in Objective-C

Can some one explain to me the difference between categories and inheritance in Objective C? I've read the entry in Wikipedia and the discussion on categories there doesn't look any different to that of inheritance. I also looked at the discussion on the topic in the book "Open iPhone Development" and I still don't get it.
Sometimes, inheritance just seems like more trouble than it is worth. It is correctly used when you want to add something to an existing class that is a change in the behaviour of that class.
With a Category, you just want the existing object to do a little more. As already given, if you just want to have a string class that handles compression, you don't need to subclass the string class, you just create a category that handles the compression. That way, you don't need to change the type of the string classes that you already use.
The clue is in the restriction that categories only add methods, you can't add variables to a class using categories. If the class needs more properties, then it has to be subclassed.(edit: you can use associative storage, I believe).
Categories are a nice way to add functionality while at the same time conforming to an object oriented principle to prefer composition over inheritance.
Edit January 2012
Things have changed now. With the current LLVM compiler, and the modern, 64-bit runtime, you can add iVars and properties to class extensions (not categories). This lets you keep private iVars out of the public interface. But, if you declare properties for the iVars, they can still be accessed / changed via KVC, because there is still no such thing as a private method in Objective-C.
Categories allow you to add methods to existing classes. So rather than subclass NSData to add your funky new encryption methods, you can add them directly to the NSData class. Every NSData object in your app now has access to those methods.
To see how useful this can be, look at: CocoaDev
One of favorite illustrations of Objective-c categories in action is NSString. NSString is defined in the Foundation framework, which has no notion of views or windows. However, if you use an NSString in a Cocoa application you'll notice it responds to messages like – drawInRect:withAttributes:.
AppKit defines a category for NSString that provides additional drawing methods. The category allows new methods to be added to an existing class, so we're still just dealing with NSStrings. If AppKit instead implemented drawing by subclassing we'd have to deal with 'AppKitStrings' or 'NSSDrawableStrings' or something like that.
Categories let you add application or domain specific methods to existing classes. It can be quite powerful and convenient.
If you as a programmer are given a complete set of source code for a code library or application, you can go nuts and change whatever you need to achieve your programming goal with that code.
Unfortunately, this is not always the case or even desirable. A lot of times you are given a binary library/object kit and a set of headers to make do with.
Then a new functionality is needed for a class so you could do a couple of things:
create a new class whole instead of a stock class -- replicating all its functions and members then rewrite all the code to use the new class.
create a new wrapper class that contains the stock class as a member (compositing) and rewrite the codebase to utilize the new class.
binary patches of the library to change the code (good luck)
force the compiler to see your new class as the old one and hope it does not depend on a certain size or place in memory and specific entry points.
subclass specialization -- create subclasses to add functionality and modify driver code to use the subclass instead -- theoretically there should be few problems and if you need to add data members it is necessary, but the memory footprint will be different. You have the advantage of having both the new code and the old code available in the subclass and choosing which to use, the base class method or the overridden method.
modify the necessary objc class with a category definition containing methods to do what you want and/or override the old methods in the stock classes.
This can also fix errors in the library or customize methods for new hardware devices or whatever. It is not a panacea, but it allows for class method adding without recompiling the class/library that is unchanged. The original class is the same in code, memory size, and entry points, so legacy apps don't break. The compiler simply puts the new method(s) into the runtime as belonging to that class, and overrides methods with the same signature as in the original code.
an example:
You have a class Bing that outputs to a terminal, but not to a serial port, and now that is what you need. (for some reason). You have Bing.h and libBing.so, but not Bing.m in your kit.
The Bing class does all kinds of stuff internally, you don't even know all what, you just have the public api in the header.
You are smart, so you create a (SerialOutput) category for the Bing class.
[Bing_SerialOutput.m]
#interface Bing (SerialOutput) // a category
- (void)ToSerial: (SerialPort*) port ;
#end
#implementation Bing (SerialOutput)
- (void)ToSerial: (SerialPort*) port
{
... /// serial output code ///
}
#end
The compiler obliges to create an object that can be linked in with your app and the runtime now knows that Bing responds to #selector(ToSerial:) and you can use it as if the Bing class was built with that method. You cannot add data members only methods and this was not intended to create giant tumors of code attached to base classes but it does have its advantages over strictly typed languages.
I think some of these answers at least point to the idea that inheritance is a heavier way of adding functionality to an existing class, while categories are more lightweight.
Inheritance is used when you're creating a new class hierarchy (all the bells and whistles) and arguably brings alot of work when chosen as the method of adding functionality to existing classes.
As someone else here put it... If you are using inheritance to add a new method for example to NSString, you have to go and change the type you're using in any other code where you want to use this new method. If, however, you use categories, you can simply call the method on existing NSString types, without subclassing.
The same ends can be achieved with either, but categories seem to give us an option that is simpler and requires less maintenance (probably).
Anyone know if there are situations where categories are absolutely necessary?
A Category is like a mixin: a module in Ruby, or somewhat like an interface in Java. You can think of it as "naked methods". When you add a Category, you're adding methods to the class. The Wikipedia article has good stuff.
The best way to look at this difference is that:
1. inheritance : when want to turn it exactly in your way.
example : AsyncImageView to implement lazy loading. Which is done by inheriting UIView.
2. category : Just want to add a extra flavor to it.
example : We want to replace all spaces from a textfield's text
#interface UITextField(setText)
- (NSString *)replaceEscape;
#end
#implementation UITextField(setText)
- (NSString *)replaceEscape
{
self.text=[self.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
return self.text;
}
#end
--- It will add a new property to textfield for you to escape all white spaces. Just like adding a new dimension to it without completely changing its way.