NSFileManager and copyItemAtPath

Today I learned a thing. I'll admit I'm a total newbie when it comes to writing code of any kind so this is exactly the type of thing that trips me up. But hey, it's easy to post about your failings when there are just so many of them.

Let me set the stage. I needed to copy a file from one place to another. Because I really only know bash, version 1 consisted of NSTask shelling out to the 'cp' command (pretty smooth, right?). As lovely and functional as that was, it wasn't very good. A better approach would be to use NSFileManager. See below for my futile first attempt.
# This doesn't work
NSString *myApp = @"/tmp/MyApp.app";
[[NSFileManager defaultManager] copyItemAtPath:myApp
                                        toPath:@"/Applications/" 
                                         error:&error];

As it turns out, the reference to path consistently means full file path. Not to be mistaken with something like directory. If you run the above code you'll get the following happy message.
com.mjr.MyAwesomeApp[50000]: Cannot make directory /Applications: File exists

So, if you come across this in your various exploits don't make the same mistake I did. Use the full file path for both copyItemAtPath as well as toPath.
# This works
NSString *myApp = @"/tmp/MyApp.app";
[[NSFileManager defaultManager] copyItemAtPath:myApp
                                        toPath:@"/Applications/MyApp.app" 
                                         error:&error];

Basically the moral of the story is don't be dumb.
~MJ

3 comments:

Joshua said...

A happy little code block here...if we make a mistake, we'll just fully qualify the path. There you go...great!

Matthew Riley said...

If only writing objective-c was as pleasant as listening to Bob Ross :-)

rileychick said...

If only I had a clue what you were talking about . . . How 'bout that travel blog?!? ; )