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

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.

Related

Is there any way to mark up a c function or obj-c method to identify it at runtime?

I'm looking for something similar to attributes in Java, to use in an objective-c environment.
Suppose I have an implementation file with a bunch of methods defined. Is there any way I can mark them up such that I could find them with introspection at runtime? Something like;
##special_method
- (void)foo
{
}
##special_method
- (void)bar
{
}
// Not special
- (void)baz
{
}
As far as I know, nothing exists, and so the best idea I have is to prefix the method name with something common:
- (void)_special_foo
{
}
- (void)_special_bar
{
}
// Not special
- (void)baz
{
}
any other interesting ideas?
I'm not sure if I understand your question correctly, but as an "interesting" possible solution, you can use a global variable that is set to a unique value identifying a specific function on entry (and optionally resetting on exit), or you can use a stack to trace these values that you can inspect at any time.
Apple's suggestion to identify private methods is to give a unique prefix:
Names of most private methods in the Cocoa frameworks have an
underscore prefix (for example, _fooData) to mark them as private.
From this fact follow two recommendations.
Don’t use the underscore character as a prefix for your private
methods. Apple reserves this convention.
If you are subclassing a
large Cocoa framework class (such as NSView or UIView) and you want to
be absolutely sure that your private methods have names different from
those in the superclass, you can add your own prefix to your private
methods. The prefix should be as unique as possible, perhaps one based
on your company or project and of the form "XX_". So if your project
is called Byte Flogger, the prefix might be BF_addObject:
I suppose you could use a similar scheme to mark certain methods as special for some sort of runtime manipulation.
DO NOT start any method names with a single leading underscore. That's an Apple internal coding convention to keep their method names from colliding with yours. If you want to differentiate your method names, just use a common prefix.
Since you are implementing the class, why not just define a method that returns a list of the special methods in that class? If you need to do subclasses, have them get the parent's list and add to it.

How do I create a file-scope class in objective-c?

I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.

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

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.

What are your naming conventions for Objective-C "private" methods?

Inheriting code from other developers has made me a firm believer in keeping as many messages as possible out of a class' public interface by means of a Class Extension. I'm also a firm believer in adopting special naming conventions for private, implementation-specific members of a class. I really like being able to tell at a glance what messages being sent and what members being referenced within the implementation context are not ever intended for public use and vice versa. If nothing else, it makes the overall semantics of a class easier for me grasp more quickly, and that's worth it.
Justification aside, I've written boatloads of classes with boatloads2 of private methods, but I've never really come up with a pattern for naming that I really love (like I do the controversial ivar_ convention for ivars). Notable examples:
#interface myClass()
// I like this, but as we all know, Apple has dibs on this one,
// and method name collisions are nasty.
- (void)_myPrivateMessage;
// The suffix version promoted by Google for ivars doesn't really translate
// well to method names in Objective-C, because of the way the method
// signature can be broken into several parts.
- (void)doWork_; // That's okay...
- (void)doWork_:(id)work with_:(id)something; // That's just ugly and tedious...
- (void)doWork_:(id)work with_:(id)something and_:(id)another; // My eyes...
// This version is suggested by Apple, and has the benefit of being officially
// recommended. Alas, I don't like it: The capital letter is ugly. I don't like
// underscores in the middle of the name. Worst of all, I have to type three characters
// before code-sense does anything more useful than inform me that I am typing.
- (void)BF_doWork;
#end
At this point, there are a kajillion different means by which I could mangle my private method names, but instead of making something up, I figured I would first take a poll for any popular conventions I may not be aware of. So, what have you used?
I don't distinguish private methods by name. Instead, I keep them out of the public interface by declaring them in the class extension portion of the .m file, thus:
#interface MyClass ()
- (void)doWork;
#end
I use double underscore for my private methods:
- (void)__doSomethingPrivate;
It almost looks like the single underscore-syntax (good readable) and at the same time confirms to the Apple guides.
I use a prefix, no underscore. The prefix is generally related to the name of the project in question. If you do use underscores, there's no need to have more than one.
I use two levels of private methods: slightly private and very private. Slightly private methods are methods which could become public, but currently aren't. They are usually convenience methods that I use internally, and I usually don't put in as much protection unless I decide to make it public. For very private methods, I ignore apple and use an underscore prefix. Since 99% of my code is in classes I create and I usually have prefixes on my class names, the chances of running into naming problems is small. When adding code to classes I didn't make, I rarely make private methods, but add a short prefix on the rare occasion that I do.
I prefix private methods with a 'p':
(void) pDoWork;
(void) pDoWork:(id)work with:(id)something;
Similarly, I use 's' for static (or class) methods:
(Universe*)sGet; // used to return singleton Universe object.
Beyond naming conventions, I declare private methods in .m files instead of .h files.
Using a fixed prefix will help to "hide" the method from the outside world but it won't prevent a method from being accidentally overridden. E.g. I once extended a class and I made a method:
- (void)private_close
{
// ...
}
The result was that the behavior of the class broke in horrible ways. But why? It turned out, the super class also had a method name private_close and I was accidentally overriding it without calling super! How should I know? No compiler warning!
No matter if your prefix is _ or __ or p or private_, if it is always the same, you will end up with problems like this one.
So I prefix private methods (and properties!) with a prefix that resembles the class name. Therefor I take the upper case letters of the class name to form the "private prefix":
ComplexFileParser -> CFP
URLDownloadTask -> URLDT
SessionController -> SC
This is still not perfectly safe, yet it is very unlikely that a subclass with a different name has the same still the same private prefix.
Also when you do frameworks, you should prefix all classes and other symbols with a framework prefix (as Apple does with NS..., CF..., CA..., SC..., UI..., etc.) and thus this class prefix is part of the private prefix as well making collisions even less likely:
Framework DecodingUtils.framework -> DU
Class ComplexFileDecoder in framework -> DUComplexFileDecoder
Private Prefix -> DUCFD
Private Method close -> - (void)DUCFD_close
Alternatively append the prefix at the end of the fist method argument name, to get better auto-completion:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2
will become
- (void)doSomethingWith_DUCFD:(Type1)var1 parameters:(Type2)var2
or always only append it to the last parameter name:
- (void)doSomethingWith:(Type1)var1 parameters_DUCFD:(Type2)var2
or (now it gets really crazy) - add a fake dummy parameter just for naming:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2 DUCFD:(id)x
where x is actually never used in the method and you pass nil for it:
[self doSomethingWith:var1 parameters:var2 DUCFD:nil];
and as it will always be the same at the end, use a pre-processor macro:
#define priv DUCFD:nil
#define PRIVATE DUCFD:nil
// ...
[self doSomethingWith:var1 parameters:var2 priv];
[self doSomethingWith:var1 parameters:var2 PRIVATE];
Prefix and suffixing works also with properties (and thus their ivar, getter/setter methods), the preproessor trick above won't, of course.
Regarding Apple recommendations. You might be interested in how Apple writes it's own code.
If you check private APIs you will see that they use underscores for private methods everywhere. Every peace of Obj-C code in iOS uses them. And in many cases those methods go through multiple iOS versions without refactoring or renaming which means it's not a temporary solution for them but rather a convention. In fact, there're three levels of private methods they use extensively - no underscore, single and double underscore.
As for other solutions like "private", class or project name prefixes - they don't use them at all. Just underscores.

Helper functions in Cocoa

What is the standard way of incorporating helper/utility functions in Obj-C classes?
I.e. General purpose functions which are used throughout the application and called by more than 1 class.
Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?
I would group similar functions as static methods in a helper class. These can then be called using the classname rather the instance name. Static methods are defined with a + instead of the usual -.
like so:
#interface HelperClass: superclassname {
// instance variables - none if all methods are static.
}
+ (void) helperMethod: (int) parameter_varName;
#end
This would be called like so.
[HelperClass helperMethod: 10 ];
As this is static you do not init/alloc the class. This has the advantage of clearly grouping like Helper functions. You could use standalone C functions but as your Application gets larger it can become a right mess! Hope this helps.
Tony
I don't see why people are avoiding creating functions. Objective-C is a superset of C, which means that C is part of it. Moreover, it's completely integrated—there's no wall between them.
Create functions! It's fine! Foundation does it. Application Kit does it. Core Animation does it. Core Media does it.
I see no reason not to.
There are a number of options for this in Objective-C. First, since Obj-C is a strict superset of C, you can define all your library functions in a separate module (source file) and happily call them from any Obj-C object/code you already have. If you create an obj-c source file (.m file) you can then call back into/use objects.
If your generic functions are logically manipulating other, established objects (for instances, operates on an NSString), you can use categories to graph your functions on already existing classes (where that makes sense).
Finally, as Tony points out, you can create classes with static methods (although I like this option the least, personally). I tend to use a mix of one an two... adding categories where appropriate and using standard functions for others. I generally only make a new class where it makes sense to design a class.