2

I'm creating a mac app that needs to create a file with the contents of another file, i'm creating it as follows:

NSString *p = @"/AfilethatEXISTS.plist"; NSString *user1 = @"~/Library/MyApp/myFile"; NSString *pT1 = [user1 stringByExpandingTildeInPath]; [[NSFileManager alloc] createFileAtPath:[NSURL URLWithString:pT1] contents:[NSData dataWithContentsOfFile:p] attributes:nil]; 

However returning no error, its not creating the file?

2 Answers 2

6

There are several things wrong with this code, but not enough context to tell you what is going wrong.

First, there should never be a file in / directly. That directory should be sacrosanct and many users will not be able to write to that directory without admin access.

Secondly, paths should be managed via the path manipulation APIs on NSString and NSURL.

Next, pT1 isn't really an URL and that is URLWithString: may be returning nil. Use fileURLWithPath: instead.

Finally, there isn't any error checking in that code and, thus, there is no way to tell how you might have discovered no error. What have you checked?

Sign up to request clarification or add additional context in comments.

Comments

2

First off, you're creating the file manager instance incorrectly. To create a new instance, you need to both allocate and initialize it.

You're trying to pass an NSURL object, which won't be created correctly since the string you're using to create it with isn't a URL. But that doesn't matter anyway, because even if the NSURL was created, -createFileAtPath:contents:attributes: expects an NSString - just pass pT1 directly.

Better still, since you're basically just copying p to pT1, use the NSFileManager method for doing that. Not only is it conceptually a better fit, it also gives you a chance to examine a returned NSError object to see what (if anything) went wrong.

NSError *error; NSFileManager *fm = [[[NSFileManager alloc] init] autorelease]; if (![fm copyFileAtPath:p toPath:pT1 error:&error]) { // If copyFileAtPath:toPath:error: returned FALSE, an error occurred, and // error will point to an NSError instance with more information } 

3 Comments

Instead of allocating and initializing an NSFileManager, just use +sharedManager. Just a heads up.
Copied straight from Apple's docs page, linked above: "In iOS and Mac OS X v 10.5 and later you should consider using [[NSFileManager alloc] init] rather than the singleton method defaultManager. Instances of NSFileManager are considered thread-safe when created using [[NSFileManager alloc] init]."
Fair enough. I guess I haven't taken a close look at the documentation in a while. I sort of assumed +defaultManager was the way to go, but you're right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.