NSString's writeToFile output doesn't show up

This is primarily about scripting, so I am writing to request help from this forum.
As the method requires an error variable which I can’t get in Applescript, I made an extension to NSString

-(BOOL)writeToUTF8File:(NSString *)path{ NSLog(@"%@", path); NSError *error; BOOL response = [self writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (error) { NSLog(@"Fail: %@", [error localizedDescription]); } if (response) { NSLog(@"YES"); } else { NSLog(@"NO"); } NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath:path] == YES) NSLog (@"File exists"); else NSLog (@"File not found"); return response; }
The path is a valid path string e.g. “Macintosh HD:Users:myUser:Desktop:validFolder:file.html” as an NSString
The NSString used here as the contents of the file is an valid html page – name it “aString”
When invoked using aString’s writeToUTF8File:path, the log indicates that the file was successfully written and reading the file into a string shows the original file is indeed there in the folder but nothing else can find the file. Using the finder shows zero files in the folder and using the terminal also find no files there.
How do I fix this problem? It could be a useful extension for Applescript.

There are two issues:

  • Cocoa methods like writeToFile: require POSIX paths, not HFS paths. The file is probably somewhere on your disk, with lots of slashes in its name.

  • You can uses out values like error in AppleScript, so there’s no need for the category. You do it like this:

Set {theResult, theError} to someString's writeToFile:thePath atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:reference
if theResult as boolean is false then
-- do something with theError

or if the error doesn’t matter:

Set theResult to someString's writeToFile:thePath atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:(missing value)
if theResult as boolean is false then
-- do what you want

This is all covered in my books (page 36 of ‘Everyday AppleScriptObjC’ or page 181 of ‘AppleScriptObjC Explored’ v5).

set contentsString to NSString's stringWithString:"This is to be the contents of the file" set aPath to NSString's stringWithString:"Macintosh HD/Users/myusername/Desktop/aFile.html" set {aBool, theError} to contentsString's writeToFile:aPath atomically:false encoding:(current application's NSUTF8StringEncoding) |error|:reference current application's NSLog("%@",(theError's localizedDescription))
This code gives the error “The file “aFile.html” doesn’t exist.”

What is it I’m missing? I though that passing a valid path string to the contents NSString would result in a file.

That’s not a valid POSIX path.