Is overriding Objective-C framework methods ever a good idea? - objective-c

ObjC has a very unique way of overriding methods. Specifically, that you can override functions in OSX's own framework. Via "categories" or "Swizzling". You can even override "buried" functions only used internally.
Can someone provide me with an example where there was a good reason to do this? Something you would use in released commercial software and not just some hacked up tool for internal use?
For example, maybe you wanted to improve on some built in method, or maybe there was a bug in a framework method you wanted to fix.
Also, can you explain why this can best be done with features in ObjC, and not in C++ / Java and the like. I mean, I've heard of the ability to load a C library, but allow certain functions to be replaced, with functions of the same name that were previously loaded. How is ObjC better at modifying library behaviour than that?

If you're extending the question from mere swizzling to actual library modification then I can think of useful examples.
As of iOS 5, NSURLConnection provides sendAsynchronousRequest:queue:completionHandler:, which is a block (/closure) driven way to perform an asynchronous load from any resource identifiable with a URL (local or remote). It's a very useful way to be able to proceed as it makes your code cleaner and smaller than the classical delegate alternative and is much more likely to keep the related parts of your code close to one another.
That method isn't supplied in iOS 4. So what I've done in my project is that, when the application is launched (via a suitable + (void)load), I check whether the method is defined. If not I patch an implementation of it onto the class. Henceforth every other part of the program can be written to the iOS 5 specification without performing any sort of version or availability check exactly as if I was targeting iOS 5 only, except that it'll also run on iOS 4.
In Java or C++ I guess the same sort of thing would be achieved by creating your own class to issue URL connections that performs a runtime check each time it is called. That's a worse solution because it's more difficult to step back from. This way around if I decide one day to support iOS 5 only I simply delete the source file that adds my implementation of sendAsynchronousRequest:.... Nothing else changes.
As for method swizzling, the only times I see it suggested are where somebody wants to change the functionality of an existing class and doesn't have access to the code in which the class is created. So you're usually talking about trying to modify logically opaque code from the outside by making assumptions about its implementation. I wouldn't really support that as an idea on any language. I guess it gets recommended more in Objective-C because Apple are more prone to making things opaque (see, e.g. every app that wanted to show a customised camera view prior to iOS 3.1, every app that wanted to perform custom processing on camera input prior to iOS 4.0, etc), rather than because it's a good idea in Objective-C. It isn't.
EDIT: so, in further exposition — I can't post full code because I wrote it as part of my job, but I have a class named NSURLConnectionAsyncForiOS4 with an implementation of sendAsynchronousRequest:queue:completionHandler:. That implementation is actually quite trivial, just dispatching an operation to the nominated queue that does a synchronous load via the old sendSynchronousRequest:... interface and then posts the results from that on to the handler.
That class has a + (void)load, which is the class method you add to a class that will be issued immediately after that class has been loaded into memory, effectively as a global constructor for the metaclass and with all the usual caveats.
In my +load I use the Objective-C runtime directly via its C interface to check whether sendAsynchronousRequest:... is defined on NSURLConnection. If it isn't then I add my implementation to NSURLConnection, so from henceforth it is defined. This explicitly isn't swizzling — I'm not adjusting the existing implementation of anything, I'm just adding a user-supplied implementation of something if Apple's isn't available. Relevant runtime calls are objc_getClass, class_getClassMethod and class_addMethod.
In the rest of the code, whenever I want to perform an asynchronous URL connection I just write e.g.
[NSURLConnection sendAsynchronousRequest:request
queue:[self anyBackgroundOperationQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *blockError)
{
if(blockError)
{
// oh dear; was it fatal?
}
if(data)
{
// hooray! You know, unless this was an HTTP request, in
// which case I should check the response code, etc.
}
/* etc */
}
So the rest of my code is just written to the iOS 5 API and neither knows nor cares that I have a shim somewhere else to provide that one microscopic part of the iOS 5 changes on iOS 4. And, as I say, when I stop supporting iOS 4 I'll just delete the shim from the project and all the rest of my code will continue not to know or to care.
I had similar code to supply an alternative partial implementation of NSJSONSerialization (which dynamically created a new class in the runtime and copied methods to it); the one adjustment you need to make is that references to NSJSONSerialization elsewhere will be resolved once at load time by the linker, which you don't really want. So I added a quick #define of NSJSONSerialization to NSClassFromString(#"NSJSONSerialization") in my precompiled header. Which is less functionally neat but a similar line of action in terms of finding a way to keep iOS 4 support for the time being while just writing the rest of the project to the iOS 5 standards.

There are both good and bad cases. Since you didn't mention anything in particular these examples will be all-over-the-place.
It's perfectly normal (good idea) to override framework methods when subclassing:
When subclassing NSView (from the AppKit.framework), it's expected that you override drawRect:(NSRect). It's the mechanism used for drawing views.
When creating a custom NSMenu, you could override insertItemWithTitle:action:keyEquivalent:atIndex: and any other methods...
The main thing when subclassing is whether or not your behaviour completes re-defines the old behaviour... or extends it (in which case your override eventually calls [super ...];)
That said, however, you should always stand clear of using (and overriding) any private API methods (those normally have an underscore prefix in their name). This is a bad idea.
You also should not override existing methods via categories. That's also bad. It has undefined behaviour.

If you're talking about categories, you don't override methods with them (because there is no way to call original method, like calling super when subclassing), but only completely replace with your own ones, which makes the whole idea mostly pointless. Categories are only useful for safely extending functionality, and that's the only use I have even seen (and which is a very good, an excellent idea), although indeed they can be used for dangerous things.
If you mean overriding by subclassing, that is not unique. But in Obj-C you can override everything, even private undocumented methods, not just what was declared 'overridable' like in other languages. Personally, I think it's nice, as I remember in Delphi and C++ I used to “hack” access to private and protected members to workaround an internal bug in framework. This is not a good idea, but at some moments it can be a life saver.
There is also method swizzling, but that's not standard language feature, that's a hack. Hacking undocumented internals is rarely a good idea.
And regarding “how can you explain why this can best be done with features in ObjC”, the answer is simple — Obj-C is dynamic, and this freedom is common to almost all dynamic languages (Javascript, Python, Ruby, Io, a lot more). Unless artificially disabled, every dynamic language has it.
Refer to the wikipedia page on dynamic languages for longer explanation and more examples. For example, an even more miraculous things possible in Obj-C and other dynamic languages is that an object can change it's type (class) in place, without recreation.

Related

How to replace ICoolBarManager

I want to customize the application toolbar to my own needs. A long time ago I played around (and did some impressive customizations) with the AbstractPresentationFactory.
However this extension point was removed and replaced with nothingness. (The documentation states its replacement is org.eclipse.e4.ui.css.swt.theme, but that extension point is useless without proper documentation.)
I debugged my application to the point of finding the interface ICoolBarManager, and lo and behold, the JavaDoc says:
This interface is internal to the framework; it should not be implemented outside the framework. This package provides a concrete cool bar manager implementation, CoolBarManager, which clients may instantiate or subclass.
Which means I can replace the implementation of ICoolBarManager somehow (why else would I need to instantiate or subclass CoolBarManager?). A possible point for doing so is ApplicationWindow#createCoolBarManager2(int), but I'm not sure where and if I ever create an ApplicationWindow.
The simple question is: How do I replace the implementation of CoolBarManager?

What is the naming convention for methods you know will appear in a later SDK?

I realize that there is some subjectivity in the question, but considering that Apple development is pretty opinionated about naming conventions I want to do this in the way that others will understand what my coding is doing. I am trying to ask the question in the most generic way, But I'll add some of my specific details in the comments in case it affects your answer.
Let's say that I am supporting both iOS 6 and iOS 7. There is a new method on an existing class that only exists in the iOS 7 SDK. Assume that implementing the functionality in a way that is "good enough" for my app is fairly straightforward. But, of course, I'd rather use the SDK version as it is likely to be better supported, more efficient, and better handle edge cases.
As documented in this Q&A it is straightforward to handle this situation.
if ([myInstance respondsToSelector:#selector(newSelector)]) {
//Use the SDK method
} else {
//Use my "good enough" implementation.
}
But I don't want to litter my code with a whole bunch of conditional invocations. It seems that it would be better to encapsulate this dynamic method selection. (Especially in my case, where the method hasn't actually shipped yet and the name/signature might change.)
My instinct is to add a class category that implements both my functionality as well as a wrapper method that implements this dynamic selection of method.
Is this the right approach? If so, what naming conventions should I use? (I obviously can't name my method the same as the iOS7 method or there would be naming collisions.)
My gut reaction is to call my wrapper method safeNewSelector and my implementation a private method called lwNewSelector (where lw is my standard class prefix). But I'd much rather use something that would be considered a standard naming convention.
My instinct is to add a class category that implements both my functionality as well as a wrapper method that implements this dynamic selection of method.
That sounds right. The naming convention for category methods is a lowercase prefix, plus underscore. So, if you are shadowing a method called doSomething:withAwesome:, you would name your category method ogr_doSomething:withAwesome: (assuming you use OGR as your common prefix).
You really must prefix category methods. If two categories implement the same method, it is undefined behavior which will be run. You will not get a compile-time or runtime error. You'll just get undefined behavior. (And Apple can, and does, implement "core" functionality in categories, and you cannot easily detect that they've done so.)
Go for a category and chose a name that is pretty unique, for example prefixed by some company/project specific prefix. Let's say the method in iOS 7 is going to be called funky and you chose the prefix foo. Then you'd do:
#implementation SomeClass(FooCategory)
- (void)foo_funky
{
if ([self respondsToSelector:#selector(funky)]) {
[self funky];
} else {
// Implementation of workaround.
}
}
#end
Now, every time you'd call foo_funky that decision needs to be made. Pretty inefficient. It just occurred to me that Objective-C can make that more efficient by messing with the runtime, kind of like method-swizzling (following code is untested):
#implementation SomeClass(FooCategory)
- (void)foo_funky
{
// Empty implementation, it will be replaced.
}
- (void)foo_myFunkyImplementation
{
// Workaround implementation in case the iOS 7 version is missing.
}
+ (void)load
{
Method realMethod, dummyMethod;
realMethod = class_getInstanceMethod(self, #selector(funky));
if (!realMethod) {
// iOS7 method not available, use my version.
realMethod = class_getInstanceMethod(self, #selector(foo_myFunkyImplementation));
}
// Get the method that should be replaced.
dummyMethod = class_getInstanceMethod(self, #selector(foo_funky));
// Overwrite the dummy implementation with the real implementation.
method_setImplementation(dummyMethod, method_getImplementation(realMethod));
}
#end
This way every time you call foo_funky the correct method is called without the overhead of responds-to-selector-and-then-call-other-method.
You could also use the runtime class modifications to add your implementation using the official name when it's not available, but I don't recommend that. It's better when you can tell by the method name that it might not be the version you're expecting.
It is a fair question indeed and I think many Objective-C debs have run into this situation.
I have used the approach that you suggest, using a class category, in several places myself. As for the naming, in most cases I put a little extra functionality into my category method, so my method names most of the time take another argument – in most cases a simple animated:(BOOL)animated added to the end of the "official" method name.
Yes, there's a risk of clashing with future SDK releases, but I wouldn't worry too much about it, Xcode's refactoring works reasonably well and you'll get a linker warning when category methods conflict.
Edit:
As Rob points out, using that naming convention is probably a good idea.

Custom performance profiler for Objective C

I want to create a simple to use and lightweight performance profile framework for Objective C. My goal is to measure the bottlenecks of my application.
Just to mention that I am not a beginner and I am aware of Instruments/Time Profiler. This is not what I am looking for. Time Profiler is a great tool but is too developer oriented. I want a framework that can collect performance data from a QA or pre production users and even incorporate in a real production environment to gather the real data.
The main part of this framework is the ability to measure how much time was spent in Objective C message (I am going to profile only Objective C messages).
The easiest way is to start timer in the beginning of a message and stop it at the end. It is the simplest way but its disadvantage is that it is to tedious and error prone - if any message has more than 1 return path then it will require to add the "stop timer" code before each return.
I am thinking of using method swizzling (just to note that I am aware that Apple are not happy with method swizzling but these profiled builds will be used internally only - will not be uploaded on the App Store).
My idea is to mark each message I want to profile and to generate automatically code for the method swizzling method (maybe using macros). When started, the application will swizzle the original selector with the generated one. The generated one will just start a timer, will call the original method and then will stop the timer. So in general the swizzled method will be just a wrapper of the original one.
One of the problems of the above idea is that I cannot think of an easy way how to automatically generate the methods to use for swizzling.
So I greatly will appreciate if anyone has any ideas how to automate the whole process. The perfect scenario is just to write one line of code anywhere mentioning the class and the selector I want to profile and the rest to be generated automatically.
Also will be very thankful if you have any other idea (beside method swizzling) of how to measure the performance.
I came up with a solution that works for me pretty well. First just to clarify that I was unable to find out an easy (and performance fast) way to automatically generate the appropriate swizzled methods for arbitrary selectors (i.e. with arbitrary arguments and return value) using only the selector name. So I had to add the arguments types and the return value for each selector, not only the selector name. In reality it should be relatively easy to create a small tool that would be able to parse all source files and detect automatically what are the arguments types and the returned value of the selector which we want to profile (and prepare the swizzled methods) but right now I don't need such an automated solution.
So right now my solution includes the above ideas for method swizzling, some C++ code and macros to automate and minimize some coding.
First here is the simple C++ class that measures time
class PerfTimer
{
public:
PerfTimer(PerfProfiledDataCounter* perfProfiledDataCounter);
~PerfTimer();
private:
uint64_t _startTime;
PerfProfiledDataCounter* _perfProfiledDataCounter;
};
I am using C++ to use that the destructor will be executed when object has exited the current scope. The idea is to create PerfTimer in the beginning of each swizzled method and it will take care of measuring the elapsed time for this method
The PerfProfiledDataCounter is a simple struct that counts the number of execution and the whole elapsed time (so it may find out what is the average time spent).
Also I am creating for each class I'd like profile, a category named "__Performance_Profiler_Category" and to conforms to "__Performance_Profiler_Marker" protocol. For easier creating I am using some macros that automatically create such categories. Also I have a set of macros that take selector name, return type and arguments type and create selectors for each selector name.
For all of the above tasks, I've created a set of macros to help me. Also I have a single file with .mm extension to register all classes and all selectors I'd like to profile. On app start, I am using the runtime to retrieve all classes that conforms to "__Performance_Profiler_Marker" protocol (i.e. the registered ones) and search for selectors that are marked for profiling (these selectors starts with predefined prefix). Note that this .mm file is the only file that needs .mm extension and there is no need to change file extension for each class I want to profile.
Afterwards the code swizzles the original selectors with the profiled ones. In each profiled one, I just create PerfTimer and call the swizzled method.
In brief that is my idea which turned out to work pretty smoothly.

Creating an Objective-C API

I have never made an API in objective-c, and need to do this now.
The "idea" is that I build an API which can be implemented into other applications. Much like Flurry, only for other purposes.
When starting the API, an username, password and mode should be entered. The mode should either be LIVE or BETA (I guess this should be an NSString(?)), then afterwards is should be fine with [MyAPI doSomething:withThisObject]; ect.
So to start it [MyAPI username:#"Username" password:#"Password" mode:#"BETA"];
Can anyone help me out with some tutorials and pointer on how to learn this best?
It sounds like what you want to do is build a static library. This is a compiled .a file containing object code that you'll distribute to a client along with a header file containing the interface. This post is a little outdated but has some good starting points. Or, if you don't mind giving away your source code, you could just deliver a collection of source files to your client.
In terms of developing the API itself, it should be very similar to the way you'd design interfaces and implementations of Objective-C objects in your own apps. You'll have a MyAPI class with functions for initialization, destruction, and all the functionality you want. You could also have multiple classes with different functionality if the interface is complex. Because you've capitalized MyAPI in your code snippet, it looks like you want to use it by calling the class rather than an instance of the class - which is a great strategy if you think you'll only ever need one instance. To accomplish this you can use the singleton pattern.
Because you've used a username and password, I imagine your API will interface with the web internally. I've found parsing JSON to be very straightforward in Objective-C - it's easy to send requests and get information from a server.
Personally I would use an enum of unsigned ints rather than a NSString just because it simplifies comparisons and such. So you could do something like:
enum {
MYAPI_MODE_BETA,
MYAPI_MODE_LIVE,
NUM_MYAPI_MODES
};
And then call:
[MyAPI username:#"Username" password:#"Password" mode:MYAPI_MODE_BETA];
Also makes it easy to check if they've supplied a valid mode. (Must be less than NUM_MYAPI_MODES.)
Good luck!

Auto-generate Objective-C method headers from implementation?

Is there a tool that will take a list of Objective-C methods and produce the corresponding header definitions?
Often when writing code in my implementation file, I find I need to add, remove, or modify method definitions. This requires the tedious (and thoroughly-automatable) step of switching back to my header file and making the exact same changes, twice.
What ever happened to DRY? What kind of tools can I use to make life easier here? Thanks.
You can try Accessorizer:
http://www.kevincallahan.org/software/accessorizer.html
It automates most work regarding properties, it might work for methods too.
Sadly, it's not free.
I don't know of any existing tools (although Interface Builder does allow you to define outlets and actions, and then generate a header and implementation skeleton for you based on those). Remember though that the implementation file can contain information that should not go in the header (such as private methods and instance variables/properties), so it would be difficult for any tool to do this in any case.
For the moment, in Xcode, you can split the window and see both side by side (in Xcode 4, this is the Assistant). Alternatively, you can press Alt-Command-UpArrow to see the corresponding file.