Is there a generic method to test for an #imported file in Objective-C - objective-c

I'm working on an extension of Core Data functionality. I've got a block of code where I'd like to test if a user's NSApplicationDelegate implements the templated managedObjectContext accessor. But I don't want to require the AppKit framework or NSApplication (I might use the functionality in command-line applications), so I'd like to wrap the block in an #ifdef.
Looking at NSApplication.h, there are #defines for NSAppKit versions (e.g. NSAppKitVersionNumber10_0). I could test for an arbitrary one of those, but that doesn't feel quite right. Is there a generic way in the preprocessor to test whether the current compilation environment includes a framework or specific header?

No, there is not, because:
The C preprocessor does not keep track of the files it has included — it just includes them and moves on
The preprocessor has no concept of "frameworks," per se, and they aren't even brought in until the linking stage anyway
The test for an AppKit version is the idiomatic way to do this sort of thing in the preprocessor.
However, i don't see why you need the preprocessor for this.
BOOL delegateImplementsAccessor = [[[NSClassFromString(#"NSApplication") sharedApplication] delegate] respondsToSelector:#selector(managedObjectContext)];

Related

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.

How to statically dump all ObjC methods called in a Cocoa App?

Assume I have a Cocoa-based Mac or iOS app. I'd like to run a static analyzer on my app's source code or my app's binary to retrieve a list of all Objective-C methods called therein. Is there a tool that can do this?
A few points:
I am looking for a static solution. I am not looking for a dynamic solution.
Something which can be run against either a binary or source code is acceptable.
Ideally the output would just be a massive de-duped list of Objective-C methods like:
…
-[MyClass foo]
…
+[NSMutableString stringWithCapacity:]
…
-[NSString length]
…
(If it's not de-duped that's cool)
If other types of symbols (C functions, static vars, etc) are present, that is fine.
I'm familiar with class-dump, but AFAIK, it dumps the declared Classes in your binary, not the called methods in your binary. That's not what I'm looking for. If I am wrong, and you can do this with class-dump, please correct me.
I'm not entirely sure this is feasible. So if it's not, that's a good answer too. :)
The closest I'm aware of is otx, which is a wrapper around otool and can reconstruct the selectors at objc_msgSend() call sites.
http://otx.osxninja.com/
If you are asking for finding a COMPLETE list of all methods called then this is impossible, both statically and dynamically. The reason is that methods may be called in a variety of ways and even be dynamically and programmatically assembled.
In addition to regular method invocations using the Objective-C messages like [Object message] you can also dispatch messages using the C-API functions from objc/message.h, e.g. objc_msgSend(str, del). Or you can dispatch them using the NSInvocation API or with performSelector:withObject: (and similar methods), see the examples here. The selectors used in all these cases can be static strings or they can even be constructed programmatically from strings, using things like NSSelectorFromString.
To make matters worse Objective-C even supports dynamic message resolution which allows an object to respond to messages that do not correspond to methods at all!
If you are satisfied with only specific method invocations then parsing the source code for the patterns listed above will give you a minimal list of methods that may be called during execution. But the list may be both incomplete (i.e., not contain methods that may be called) as well as overcomplete (i.e., may contain methods that are not called in practice).
Another great tool is class-dump which was always my first choices for static analysis.
otool -oV /path to executable/ | grep name | awk '{print $3}'

Can I use an application as a library (Mac, Objective-c)?

Is there a way to load classes from a mac app, and use them in a different mac app?
I'd like to make an Automator action that accesses some of the classes in my mac app, and this seems like the sort of way I'd ideally do it (means you have to have bought my app to use the Automator action, etc.)
Depending on what you want to do (I'm not quite clear), a Service might do the trick for you. You make a helper app which can pass data back and forth with your app, using a shared pasteboard. You can get a fairly wide range of action, because you can pass any object that conforms to the NSPasteboardWriting and NSPasteboardReading protocols; as it says there in the docs, NSString, NSAttributedString, NSURL, NSColor, NSSound, and NSImage are already available for you, and of course you can write a custom class that suits your needs exactly.
Have you tried creating a stand-alone Automator plugin project, or tried adding an Automator bundle target to your application's project?
I'm assuming that you want to create Automator actions for your main app, but are unclear how you get these actions to interact with your application (or with the classes present in your application).
There are 3 basic types of Automator actions: AppleScript-based, shell-script based, and Objective-C based. You'll most likely want to make yours Objective-C-based, which will allow you to easily incorporate other Objective-C code from your main application into the action itself (see Implementing an Objective-C Action). (Note that by default, when you add a new target for an automator bundle, it's an AMAppleScriptAction type).
To see how an Objective-C automator action is set up compared to an AppleScript-based action, you might want to try creating a separate standalone project.
Let's say your app is document-based, and uses the KWDocument class, which exposes a method named -duplicateObjects:(NSArray *)objects toDocument:(KWDocument *)destDocument;. You also have a KWRegistrationManager that knows whether your app is registered or not. And let's say you want to create an automator action that's called "Duplicate Objects to Document". The action will be implemented in KWDuplicateObjectsToDocument, which is as a subclass of AMBundleAction. In the Info.plist for Duplicate Objects to Document.action, the NSPrincipalClass will be KWDuplicateObjectsToDocument.
KWDuplicateObjectsToDocument.h will look something like:
#import <Cocoa/Cocoa.h>
#import <Automator/AMBundleAction.h>
#interface KWDuplicateObjectsToDocument : AMBundleAction {
}
- (id)runWithInput:(id)input fromAction:(AMAction *)anAction
error:(NSDictionary **)errorInfo;
#end
And your KWDuplicateObjectsToDocument.m will look something like this:
#import "KWDuplicateObjectsToDocument.h"
#import "KWDocument.h"
#import "KWRegistrationManager.h"
#implementation KWDuplicateObjectsToDocument
- (id)runWithInput:(id)input fromAction:(AMAction *)anAction
error:(NSDictionary **)errorInfo {
if (![[KWRegistrationManager defaultManager] isRegistered]) {
return nil;
}
// eventually you'll call
// duplicateObjects:toDocument:
return input;
}
#end
You'll need to make sure that the necessary classes you use (such as KWRegistrationManager, KWDocument, etc.) are compiled and included as part of the build process for this bundle.
Basically, no: you cannot link with an executable.
An application binary is in a specific format.
And that format is different from the static or shared library format.
It means you won't be able to load any code parts from an application binary, as you would with a library.
Take a look at distributed objects. Your application could vend one or more objects that your Automator action could use. I've never tried it with Automator, but it's a very elegant system that hasn't gotten a lot of attention in recent years. I think it's definitely worth a look.
One cool aspect of distributed objects is that the application could be running on the same computer if you wish, but it could just as easily be running on a different computer, perhaps even one that's very far away.
You could make certain behavior from you app accessible via Applescript, but accessing the the actual classes is not possible in the way I think you mean. I get the impression that you mean accessing the classes loaded into the memory of your running app. This is not possible on OS X (or any UNIX-like system). Applications run at the user level. Processess at the user level are not able to read memory from other processes. The components of the OS that need to do this sort of thing run at kernel level.
If you are just trying to reuse the code, you could build the parts you want to share into a static library, and others could link against it and share your code.
EDIT:
From NSGod's answer it seems that you can use the same approach that makes it accessible via Applescript and make it accessible via Obj-C. That looks pretty cool.

Xcode: Possible to auto-create stubs for methods required by Protocol interface?

Coming from an Eclipse / Java background, one of my favorite features is the ability to quickly stub out all the methods required by an interface. In Eclipse, I can choose 'Override / implement' from the source menu to generate stub methods for any method of the Interface.
I'd like to do the same thing in Objective-C. For instance, if I declare a class that implements the 'NSCoding' protocol, I'd like to have Xcode automatically generate the methods required to implement this Protocol. It's frustrating to have to look-up and then copy/paste the signatures of the required methods every Protocol that I'm trying to implement.
I've been trying for awhile to find out if this is possible, but haven't found anything promising yet. Is this possible in XCode?
I believe that Accessorizer will do what you want.
Accessorizer will write the encode and decode methods for ivars passed to it (NSCoding protocol and for NSDocument archiving). It will also generate string constants either static or #define with a custom prefix; copyWithZone:; and other things if you need - all from a simple shortcut via Services or from the toolbar. Accessorizer keyed archiving
Not the direсt answer, just hint:
Out of the box XCode can't.
But AppCode can.
It can do this things automatically (with your permission, of course).
If some methods of protocol marked as #required - AppCode will highlight the implementation and suggest to implement this methods.
#optional methods also available to implement automatically (shortcut: control + I).
Your can create scripts for the scripting menu item in AppleScript, Perl, Python, Ruby, or any other scripting language that go in the scripting menu.
Your could place the insertion point in the .m file and have the script look up the corresponding .h file. Locate the protocols supported and so forth...
MacTech ran an article in 2007 Xcode Menu Scripts
Xcode 3.2 will autocomplete known method implementations. In other words, if the method is declared somewhere (for example, in a protocol), when you start to type it in a .m file, Xcode 3.2 will autocomplete the method signature for you. This isn't quite what you asked for, but it is awfully handy.
I'm also looking for a way to generate method stubs for the protocols in my header file. I checked out Accessorizer and it looks to be a handy tool but unless I missed something I didn't find a way to get it to generate method stubs for a protocol.
Eric, If you found another solution please post what you found. It's amazing to me that XCode doesn't already have this built into the IDE.
Since the accepted answer's given link does not work anymore (and is redirected to an ad), here's another good explanation on how to use accessorizer to create protocol method stubs.
Based on AllanCraig's "Create #property, #synthesize & dealloc from Variable Declaration" ruby script, I made one to generate implementation stubs from interface ones: http://pastebin.com/4T2LTBh6
How to use?
Setup the script on your XCode (Shell Script) and assign a shortcut for it (e.g. CMD+5).
Select lines from your interface file in which you want to generate the implementation, and press the hotkey.
Your .m will contain your selected methods.
I know this is an old question but if you'd like to always see the latest definitions just right click on the class in question and Jump to Definition. Here lyes all the current non-deprecated functions so you aren't relying on a 3rd party to stay up to date.
In My case Below style helps me much, In a sense solved my problem.
Suppose you have following method declaration:
+(DBManager*)getSharedInstance;
From Implementation file you start typing +ge and xcode will automatically choose method
+(DBManager*)getSharedInstance;

Objective-C equivalent of Java packages?

What is the Objective-C equivalent of Java packages? How do you group and organize your classes in Objective-C?
Question 1: Objective-C equivalent of Java packages?
Objective-C doesn't have an equivalent to Java packages or C++ namespaces. Part of the reason for this is that Objective-C was originally a very thin runtime layer on top of C, and added objects to C with minimum fuss. Unfortunately for us now, naming conflicts are something we have to deal with when using Objective-C. You win some, you lose some...
One small clarification (although it's not much for consolation) is that Objective-C actually has two flat namespaces — one for classes and one for protocols (like Java's interfaces). This doesn't solve any class naming conflicts, but it does mean you can have a protocol and class with the same name (like <NSObject> and NSObject) where the latter usually adopts ("implements") the former. This feature can prevent "Foo / FooImpl" pattern rampant in Java, but sadly doesn't help with class conflicts.
Question 2: How to [name] and organize Objective-C classes?
Naming
The following rules are subjective, but they are decent guidelines for naming Objective-C classes.
If your code can't be run by other code (it's not a framework, plugin, etc. but an end-user application or tool) you only need to avoid conflicts with code you link against. Often, this means you can get away with no prefix at all, so long as the frameworks/plugins/bundles you use have proper namespaces.
If you're developing "componentized" code (like a framework, plugin, etc.) you should choose a prefix (hopefully one that's unique) and document your use of it someplace visible so others know to avoid potential conflicts. For example, the CocoaDev wiki "registry" is a de facto public forum for calling "dibs" on a prefix. However, if your code is something like a company-internal framework, you may be able to use a prefix that someone else already does, so long as you aren't using anything with that prefix.
Organization
Organizing source files on disk is something that many Cocoa developers unfortunately gloss over. When you create a new file in Xcode, the default location is the project directory, right beside your project file, etc. Personally, I put application source in source/, test code (OCUnit, etc.) in test/, all the resources (NIB/XIB files, Info.plist, images, etc.) in resources/, and so on. If you're developing a complex project, grouping source code in a hierarchy of directories based on functionality can be a good solution, too. In any case, a well-organized project directory makes it easier to find what you need.
Xcode really doesn't care where your files are located. The organization in the project sidebar is completely independent of disk location — it is a logical (not physical) grouping. You can organize however you like in the sidebar without affecting disk location, which is nice when your source is stored in version control. On the other hand, if you move the files around on disk, patching up Xcode references is manual and tedious, but can be done. It's easiest to create your organization from the get-go, and create files in the directory where they belong.
My Opinion
Although it could be nice to have a package/namespace mechanism, don't hold your breath for it to happen. Class conflicts are quite rare in practice, and are generally glaringly obvious when they happen. Namespaces are really a solution for a non-problem in Objective-C. (In addition, adding namespaces would obviate the need for workarounds like prefixes, but could introduce a lot more complexity in method invocation, etc.)
The more subtle and devious bugs come from method conflicts when methods are added and/or overridden, not only by subclasses, but also be categories, which can cause nasty errors, since the load order of categories is undefined (nondeterministic). Implementing categories is one of the sharpest edges of Objective-C, and should only be attempted if you know what you're doing, particularly for third-party code, and especially for Cocoa framework classes.
They use long names...
Article on coding style & naming in Cocoa / Objective-C
Discussion whether Obj-C needs namespaces (deleted, archive here)
See
What is the best way to solve an Objective-C namespace collision?
for a discussion of how Objective-C has no namespaces, and the painful hacks this necessitates.
Unfortuantely objective c doesn't have any equivalent to namespace of C#,c++ and package of java....
The naming collisions could be solved by giving contextual name for example if u gonna give a name to method it should imply the class and module that it comes in so that...these problems could be avoided.
Go through the following url to know more on naming convention as advised by apple
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html
What about something like this (inside a directory)?
#define PruebaPaquete ar_com_oxenstudio_paq1_PruebaPaquete
#interface ar_com_oxenstudio_paq1_PruebaPaquete : NSObject {
and importing it like this:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
PruebaPaquete *p = [[PruebaPaquete alloc] init];
and when you have name collision:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
#import "ar/com/oxenstudio/paq2/PruebaPaquete.h"
ar_com_oxenstudio_paq1_PruebaPaquete *p = [[ar_com_oxenstudio_paq1_PruebaPaquete alloc] init];
ar_com_oxenstudio_paq2_PruebaPaquete *p2 = [[ar_com_oxenstudio_paq2_PruebaPaquete alloc] init];
Well, I think all the other answers here seem to focus on naming collisions, but missed at least one important feature, package private access control that java package provides.
When I design a class, I find it is quite often that I just want some specific class(es) to call its methods, b/c they work together to achieve a task, but I don't want all the other unrelated classes to call those methods. That is where java package access control comes in handy, so I can group the related classes into a packaged and make those methods package private access control. But there is no way to do that in objective c.
Without package private access control I find it is very hard to avoid people writing code like this, [[[[[a m1] m2] m3] m4] m5] or [a.b.c.d m1].
Update: Xcode 4.4 introduced "An Objective-C class extension header", in my opinion, that is in some way to provide "package private access control", so if you include the extension header, you can call my "package private" methods; if you only include my public header, you can only call my public API.