How to conditionally use a new Cocoa API - objective-c

In 10.6 Apple added +[NSPropertyListSerialization dataWithPropertyList:format:options:error:] and labeled the older +[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:] as obsolete and soon to be deprecated. One way to use the newer call on 10.6 and above, and still run on earlier OS releases, would be something like this:
if ([NSPropertyListSerialization respondsToSelector:#selector(dataWithPropertyList:format:options:error:)]) {
data = [NSPropertyListSerialization dataWithPropertyList:dict
format:NSPropertyListXMLFormat_v1_0
options:0
error:&err];
} else {
data = [NSPropertyListSerialization dataFromPropertyList:dict
format:NSPropertyListXMLFormat_v1_0
errorDescription:&errorDescription];
}
Built against the 10.4 SDK (for compatibility with that release), this results in: warning: 'NSPropertyListSerialization' may not respond to '+dataWithPropertyList:format:options:error:' And, worse, since the compiler does not know about this selector, it may pass the arguments incorrectly.
Is NSInvocation the approved/best way to call new APIs that, as far as the SDK is concerned, don't yet exist?

IIRC, you want to use the 10.6 SDK and set your deployment target (MACOSX_DEPLOYMENT_TARGET) to 10.4 so the 10.5/10.6 symbols are weak-linked. Then you can use the respondsToSelector: stuff and not get warnings.
Make sure you're checking that the object can respond to the selector, of course, or you will crash on 10.4/10.5.

One other way of doing things is to declare the missing method yourself as a category of the class in question. This will get the compiler to stop complaining about not finding the method, though of course you'll still need the runtime check you're already doing to avoid actually calling the method. You might also want to wrap such a declaration using availability macros, so that it will be ignored once you do move up to using the 10.5/10.6 SDK and you won't get a different compiler complaint down the line. That would look something like this:
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4 //ignore when compiling with the 10.5 SDK or higher
#interface NSPropertyListSerialization(MissingMethods)
+ (NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(NSError **)error;
#end
#endif

Related

Objective-C Scripting Bridge and Apple Remote Desktop

Trying to automatically view a computer in Apple Remote Desktop via Scripting Bridge in Objective-C with this:
#try {
SBApplication *RD = [SBApplication applicationWithBundleIdentifier:#"com.apple.RemoteDesktop"];
// (code to check for ARD running and installed omitted here)
[RD activate]; // works just fine
RemoteDesktopComputer *computer = [[[RD classForScriptingClass:#"computer"] alloc] initWithProperties:
[NSDictionary dictionaryWithObjectsAndKeys:
ipAddress,#"InternetAddress", // looked up from header
nil
]
];
// attempt to add it to a container first:
[(SBElementArray*)[(RemoteDesktopApplication*)RD computers] addObject:computer];
// this is what raises the exception:
[computer observeZooming:Nil];
}
#catch (NSException *e) {
NSLog(#"Exception: %#", [e description]);
}
Running this yields the following exception in the log:
Exception: *** -[SBProxyByClass observeZooming:]: object has not been added to a container yet; selector not recognized [self = 0x6050004819b3]
I've done as much research as there is available on this subject and have learned that SB isn't the easiest to deal with because of how it's wired under the hood, but any experts or veterans of native Scripting Bridge (no third party frameworks or languages other than obj-c, please) is much appreciated.
All prerequisites like linking to the ScriptingBridge.framework and importing Remote Desktop.h are performed - the typecasts are to avoid what appear to be unavoidable link-time errors when building...
Edit 1: Reading the documentation on SBObject (parent of RemoteDesktopComputer) says that it's a reference rather than an actual instance, which you can fetch by calling SBObject's get method (returns id). So I tried running this as well but unfortunately received the same results:
[[computer get] observeZooming:Nil];
Here's the documentation on SBObject: https://developer.apple.com/library/mac/documentation/cocoa/Reference/SBObject_Class/SBObject/SBObject.html#//apple_ref/occ/instm/SBObject/get
Still trying...
(FWIW, I already had the following How To written up, so I'm leaving it here for future reference.)
How to use AppleScript-ObjC in place of Scripting Bridge
Scripting Bridge is, at best, an 80/20/80 "solution" (i.e. 80% of the time it works, 20% of the time it fails, and 80% of the time you've no idea why). There's little point trying to argue with SB when it breaks on stuff that works perfectly well in AppleScript - the Apple engineers responsible designed it that way on purpose and simply refuse to accept they broke spec [1] and screwed up. As a result, the AppleScript language, for all its other deficiencies, remains the only supported solution that is guaranteed to speak Apple events correctly [2].
Fortunately, since OS X 10.6 there has been another option available: use ObjC for all your general programming stuff, and only call into AppleScript via the AppleScript-ObjC bridge for the IPC stuff.
From the POV of your ObjC code, your AppleScript-based ASOC 'classes' are more or less indistinguishable from regular ObjC classes. It requires a bit of fiddling to set up, and you'll pay a bit of a toll when crossing the bridge, but given the crippled, unreliable nature of the alternatives, it's the least horrid of the supported options for anything non-trivial.
Assuming you've already got an existing ObjC-based project, here's how to add an ASOC-based class to it:
In Targets > APPNAME > Build Phases > Link Binary With Libraries, add AppleScriptObjC.framework.
In Supporting Files > main.m, add the import and load lines as shown:
#import <Cocoa/Cocoa.h>
#import <AppleScriptObjC/AppleScriptObjC.h>
int main(int argc, const char * argv[]) {
[[NSBundle mainBundle] loadAppleScriptObjectiveCScripts];
return NSApplicationMain(argc, argv);
}
To define an ASOC-based class named MyStuff that's callable from ObjC, create a MyStuff.h interface file that declares its public methods:
// MyStuff.h
#import <Cocoa/Cocoa.h>
#interface MyStuff : NSObject
// (note: C primitives are only automatically bridged when calling from AS into ObjC;
// AS-based methods with boolean/integer/real parameters or results use NSNumber*)
-(NSNumber *)square:(NSNumber *)aNumber;
#end
along with a MyStuff.applescript file containing its implementation:
-- MyStuff.applescript
script MyStuff
property parent : class "NSObject"
on square_(aNumber)
return aNumber ^ 2
end square_
end script
Because the MyStuff class doesn't have an ObjC implementation, the linker can't link your ObjC code to it at build-time. Instead, use NSClassFromString() to look up the class object at run-time:
#import "MyClass.h"
...
MyStuff *stuff = [[NSClassFromString(#"MyStuff") alloc] init];
Otherwise it's pretty much indistinguishable from a native ObjC class in normal use:
NSNumber *result = [stuff square: #3];
NSLog(#"Result: %#", result);
HTH
--
[1] Apple management broke up the original AppleScript team shortly after its initial release, causing its designers to quit in response, so a lot of knowledge of precisely how this stuff should work was lost. In particular, a full, formal specification was never produced for application developers to follow when designing their scripting support, so all they could do was use personal judgement and best guesses, then test against AppleScript to check it worked as hoped. Thus, AppleScript's own Apple event bridge is the de facto specification that every single scriptable app has been implemented against in the last twenty years, so the only way that other AE bridges can ever work correctly is if they mimic AS's own bridge down to every last query and quirk - a lesson, unfortunately, that the current AS team have repeatedly failed to understand [2].
[2] JavaScript for Automation's Apple event supported is equally crappy and busted, incidentally.
Scripting Bridge is a defective, obfuscated mess, so when an application command fails to work you've no idea if the problem is SB being defective or the application itself being buggy or simply requiring you to phrase it in a different way.
Therefore, the first step is to write a test script in AS to see it works there. If it does, it's SB that's crap; if not, try fiddling with your AS code (e.g. try phrasing the reference for the at parameter in different ways, or omitting it entirely) till it does.
You should also ask on Apple's AppleScript Users and ARD mailing lists and anywhere else that ARD scripters are likely to hang out, as most apps' scripting documentation is grossly inadequate, so a lot of knowledge of how to do things is word of mouth. (The guy you really want to talk to is John C Welch, aka #bynkii, as he's the guru of ARD scripting.)

Private Methods in Objective-C, in Xcode 4.3 I no longer need to declare them in my implementation file ?

I have a lot question marks tolling above my head.
What I don't get is before xcode 4.3 I needed to declare forward declarations (for private methods) in my implementation file.
Like in my .m file:
// deleting this with xcode 4.3 the below code still does work
// in previous versions i had to put this because otherwise the compiler can't find methodFirst
#interface DetailViewController ()
- (void)methodFirst;
- (void)methodSecond;
#end
#implementation DetailViewController
- (void) methodSecond
{
// if i delete the forward declaration now adays i dont get a compiler error that he cant find method first
[self methodFirst];
}
- (void) methodFirst
{
}
#end
Now it seems I don't need to do that anymore? Did Apple update the compiler so that it isn't needed anymore to put forward declarations?
I can't find any reference to an official Apple source about this change. I wonder what other people have encountered in their new environment.
As of the LLVM Compiler version shipped with Xcode 4.3, if you try to call a method that the compiler has not previously seen, it will look in the rest of the current #implementation block to see if that method has been declared later. If so, then it uses that, and you don't get a warning. Hence, as of Xcode 4.3, there's much less need to pre-declare your internal methods. Clearly, you still need to declare methods that are publicly exposed to other classes.
This change was noted in the release notes of some of the Xcode 4.3 betas, but apparently didn't make it into the "What's New in Xcode 4.3" final documentation.
Unlike has been suggested in other answers, this is not just an "Undeclared Selector" warning that has been turned off by default. In fact, if you're using ARC, unrecognized selectors are still hard errors. Try calling [self myNonexistentMethod] and you'll see; the compiler still complains.
There aren't any private methods in Objective-C. What you're thinking of is the class continuation, the "nameless" category interface you can declare in your .m file to declare methods that will be in the class implementation, but that aren't in the public interface.
There's never been a requirement to declare methods before they're used. However, it's always been a good idea, and the compiler has a warning flag to indicate when methods that haven't been seen are used. The reason is to do with the operating system's calling convention for functions. Different types, such as structures, floating point numbers, integer numbers, and pointers, can all be handled in different ways when they are the arguments to or return values from functions. Indeed, on different computers and in different operating systems, they are handled in different ways. To know how to handle the arguments and return values for an Objective-C method, the compiler needs to know the signature for that method: how many arguments of what types it takes, and what type it returns.
If it hasn't seen a declaration of the method, then the compiler will need to make a guess. If that guess is incorrect, then it can end up putting the wrong values into the arguments, or interpreting the return value incorrectly, or trying to take something off the stack that doesn't exist.

Is it possible to have an Objective-C Category that is only loaded if the method doesn't already exist?

On a past project (pre-iOS 4.0), I wrote the following category method on NSSortDescriptor:
+ (id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending;
When Apple released the iOS SDK 4.0, it included the exact same method (which presumably does exactly the same thing). Is it possible to write a category that is only added to the runtime either if you're running a particular OS version, or probably more to the point, if there isn't already a method declared with the same signature?
In this case, it's probably safe to override the sortDescriptorWithKey:ascending: method with a category, which will give both iOS 3 and iOS 4 support, since my version will almost certainly do the same thing. I'd still prefer not to mess with system defined methods if possible, due to the (unlikely) possibility of breaking things in edge cases.
Joshua’s answer will work well, but if you want to get really fancy, you can use the dynamic nature of Objective-C to modify the NSSortDescriptor class to your liking:
#import <objc/runtime.h>
SEL theSelector = #selector(sortDescriptorWithKey:ascending:);
if ( ! [NSSortDescriptor instancesRespondToSelector:theSelector]) {
class_addMethod([NSSortDescriptor class],
theSelector,
(IMP)mySortDescriptorWithKey,
"##:#B");
}
Of course, that depends on a C function:
id mySortDescriptorWithKeyAscending(id self, SEL _cmd, NSString *key, BOOL ascending) {
// Put your code here.
}
DISCLAIMER: I have not tried to compile any of this.
DISCLAIMER II: This may be frowned upon by Apple in terms of App Store submission.
Not directly, no.
The way I'd recommend doing this would be to have a my_sortDescriptorWithKey: which can then check if the class responds to sortDescriptorWithKey: and uses that if it does, otherwise use your own implementation.

Conditionally overriding a system method via categories in Objective-C?

Is there a way to provide a method implementation (that bears the exact same name of a method defined by the framework) only when the method isn't already defined in the system? For example method [NSSomeClass someMethod:] exists only in Mac OS X 10.6 and if my app runs in 10.5, I will provide that method's definition in a category. But when the app runs in 10.6, I want the OS-provided method to run.
Background: I'm creating an app targeted for both 10.5 and 10.6. The problem is that I recently realized that method +[NSSortDescriptor sortDescriptorWithKey:ascending:] only exists in 10.6 and my code is already littered by that method call. I could provide a default implementation for it (since this time it's not too difficult to implement it myself), but I want the "native" one to be called whenever my app runs on 10.6. Furthermore if I encounter similar problems in the future (with more difficult-to-implement-myself methods), I might not be able to get away with providing a one-liner replacement.
This question vaguely similar to Override a method via ObjC Category and call the default implementation? but the difference is that I want to provide implementations only when the system doesn't already have one.
Thanks.
I would compile +[NSSortDescriptor sortDescriptorWithKey:ascending:] in a category into a separate bundle. Then at the very beginning of your main, check if the NSSortDescriptor class has the sortDescriptorWithKey:ascending: method with respondsToSelector:. If it's not implemented (i.e. you are running on < 10.6), then load the bundle with -[NSBundle loadAndReturnError:].
This way, you will run the OS-provided method on 10.6 and your implementation on 10.5.
Yes, this is possible. Since you are targetting 10.5+ I'm assuming you are using the ObjC2 runtime, which makes it fairly straightforward.
The Objective-C Runtime Reference has all the methods you will need. Specifically, you can use class_getClassMethod or class_getInstanceMethod to see if the method already exists, and then class_addMethod to bind your implementation to that selector if the class doesn't already have it.
Alternatively, you could just do a find and sub -[NSSortDescriptor initWithKey:ascending:] then add the appropriate release statement.
It's more cumbersome to implement but far less fragile and error prone than altering the class itself. That is especially true if you've never done that before. You'll probably spend more time coming up to speed on the override than you would just doing the find.
think about compromise between changing initWithKey:ascending: method and and adding new method at runtime - just subclass NSSortDescriptor and replace all NSSortDescriptor calls with NSMySortDescriptor;
//NSMySortDescriptor.h
#interface NSMySortDescriptor : NSSortDescriptor {
}
- (id)initWithKey:(NSString *)keyPath ascending:(BOOL)ascending
#end
//NSMySortDescriptor.m
#implementation NSMySortDescriptor
- (id)initWithKey:(NSString *)keyPath ascending:(BOOL)ascending{
// check if super i.e. has initWithKey:ascending: method
if( [NSSortDescriptor instancesRespondToSelector:#selector(initWithKey:ascending:)] ) {
[NSSortDescriptor initWithKey:ascending:];
}
else{
// your custom realization for Mac OS X 10.5
//...
}
}
#end

Suppressing "'…' is deprecated" when using respondsToSelector

I'm supporting 10.4+ by picking the most-current API at runtime:
if ([fileManager respondsToSelector:#selector(removeItemAtPath:error:)])
[fileManager removeItemAtPath:downloadDir error:NULL];
else
[fileManager removeFileAtPath:downloadDir handler:nil];
In this case, 10.5 and up will use removeItemAtPath:error: and 10.4 will use removeFileAtPath:handler:. Great, but I still get compiler warnings for the old methods:
warning: 'removeFileAtPath:handler:' is deprecated [-Wdeprecated-declarations]
Is there a syntax of if([… respondsToSelector:#selector(…)]){ … } else { … } that hints the compiler (Clang) to not warn on that line?
If not, is there a way to tag that line to be ignored for -Wdeprecated-declarations?
After seeing some of the answers, let me clarify that confusing the compiler into not knowing what I'm doing is not a valid solution.
I found an example in the Clang Compiler User's Manual that lets me ignore the warning:
if ([fileManager respondsToSelector:#selector(removeItemAtPath:error:)]) {
[fileManager removeItemAtPath:downloadDir error:NULL];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[fileManager removeFileAtPath:downloadDir handler:nil];
#pragma clang diagnostic pop
}
You could declare a separate file that is designated for calling deprecated methods and set the per-file compiler flags in Xcode to ignore -Wdeprecated-declarations. You can then define a dummy function in that file to call the deprecated methods, and thereby avoid the warnings in your real source files.
I'm not sure if clang is smart enough to catch this, but if it's not, you could try using performSelector:withObject:withObject: or building and invoking an NSInvocation object.
You could just cast fileManager to an id — ids are able to refer to any Objective-C object, so the compiler isn't supposed to check methods which are called on one:
[(id)fileManager removeItemAtPath:downloadDir error:NULL];
shouldn't raise any warnings or errors.
Of course, this raises other problems — namely, you lose all compile-time checking for methods called on the id. So if you misspell you method name, etc, it wont be caught until that line of code is executed.
If you consider any form of "confusing" the compiler to be an invalid solution, you're probably going to have to live with the warning. (In my book, if you asking how to get rid of a warning, it's unwise to look a gift horse in the mouth and say something is invalid just because it doesn't look like you'd expect.)
The answers that work at runtime involve masking the operation that's happening with dynamic dispatch so the compiler doesn't complain about the deprecated call. If you don't like that approach, you can turn off "Warn About Deprecated Functions" in your Xcode project or target settings, but that's generally a bad idea. You want to know about deprecated APIs, but in this case you want to use it without warning. There are easy and hard ways to do this, and odds are you'd consider all of them "invalid" in some form, but that doesn't prevent them from being effective, even correct. ;-)
One possible way to avoid the warnings yet still select at runtime is to use objc_msgSend() directly:
objc_msgSend(fileManager, #selector(removeFileAtPath:error:), downloadDir, nil];
This is what the Objective-C runtime does under the covers anyway, and should accomplish the result you want with a minimum of fuss. You can even leave the original line commented above it for clarity. I know the documentation says, "The compiler generates calls to the messaging function. You should never call it directly in the code you write." You alone have to decide when it's okay to bend the rules.