开发者

More Detailed Error From createFileAtPath?

开发者 https://www.devze.com 2022-12-13 05:49 出处:网络
Is there anyway to get more detailed error data back from \"createFileAtPath\" I was kind of expecting an NSError? Currently I am using the BOOL return value.

Is there anyway to get more detailed error data back from "createFileAtPath" I was kind of expecting an NSError? Currently I am using the BOOL return value.

success = [fileMan createFileAtPath:fileOnDisk contents:dBuffer attributes:nil];
if(success == YES) NSLog(@"FileCreated");
else {
    NSLog(开发者_JAVA百科@"ERROR: Failed to create file");
    return 1;
}

gary


I agree... I'd love to have a function for this that accepts NSError!

Errors returned in this case are usually one of the POSIX errors declared in errno.h (errno is automatically included for you as part of the Cocoa or Foundation headers).

To see the error, use the strerror function from errno.h and reference the global errno integer, which is set by the low-level POSIX io functions when a problem occurs:

if (![fm createFileAtPath:@"/etc/foobar.txt" contents:data attributes:nil]) 
{
    NSLog(@"Error was code: %d - message: %s", errno, strerror(errno));
}

// output will be: Error was code: 13 - message: Permission denied

The list of error code constants are listed in the in the Error Handling Programming Guide for Cocoa (in addition to the errno.h header itself).


You're not supposed to use that method; they forgot to put this in the main docs (!), but if you read the Apple header file you find this comment:

/* These methods are provided here for compatibility. The corresponding methods on NSData which return NSErrors should be regarded as the primary method of creating a file from an NSData or retrieving the contents of a file as an NSData. */

So, instead, Apple expects you to use this (which, from testing, appears to function exactly the same - except that it's located in a bizarre class where you'd never think to look for it (I want to create an empty file ... so I have to ... instantiate a nil NSData object? What?) it has an NSError object):

https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/instm/NSData/writeToFile:options:error:

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号