我正在尝试将数据保存到由NSFileManager创建的目录中,但是当我尝试检索数据和NSLog时却得到null。另外,当您创建目录时,是否意味着您在指定的url路径上创建了一个文件夹?这是我正在使用的代码

NSError *error = nil;
NSFileManager *manager = [[NSFileManager alloc] init];
NSArray *urlsArray = [manager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSLog(@"%@", urlsArray);
// This will create a new url and append a photo title to the end
NSURL *url = [[urlsArray lastObject] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@", [self.recentPhoto objectForKey:FLICKR_PHOTO_TITLE]]];
NSLog(@"%@", url);
NSString *urlString = [NSString stringWithFormat:@"%@", [url absoluteString]];
NSLog(@"%@", urlString);
//create the directory
if(![manager fileExistsAtPath:urlString isDirectory:YES]){
    BOOL success = [manager createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:&error];
    if (!success) {
        NSLog(@"Error creating data path: %@", [error localizedDescription]);
    }
}
//get url for a photo image and then store it.
NSURL *imageURL = [FlickrFetcher urlForPhoto:self.recentPhoto format:FlickrPhotoFormatLarge];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
[imageData writeToURL:url atomically:YES];
//get data to check if its stored
NSData *checkImageData = [[NSData alloc] initWithContentsOfURL:url];
//This returns null
NSLog(@"%@", checkImageData);
//this returns 0
NSLog(@"%d", [manager isReadableFileAtPath:urlString]);

最佳答案

您的代码有几个问题。

这个:

NSURL *url = [[urlsArray lastObject] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@", [self.recentPhoto objectForKey:FLICKR_PHOTO_TITLE]]];


应该:

NSURL *url = [[urlsArray lastObject] URLByAppendingPathComponent:[self.recentPhoto objectForKey:FLICKR_PHOTO_TITLE]];


这个:

NSString *urlString = [NSString stringWithFormat:@"%@", [url absoluteString]];


应该:

NSString *urlString = [url path];


这个:

BOOL success = [manager createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:&error];


应该:

BOOL success = [manager createDirectoryAtURL:[url URLByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];


这个:

[imageData writeToURL:url atomically:YES];


应该:

NSError *error = nil;
BOOL res = [imageData writeToURL:url options:NSDataWritingAtomic error:&error];
if (!res) {
    NSLog(@"Unable to write to %@: %@", url, error);
}


主要问题是使用absoluteString而不是path将URL转换为文件路径。在创建目录时,辅助服务器正在传递文件名而不是路径。不必要地使用stringWithFormat:不会引起任何问题,但请立即改掉这种习惯。仅在实际需要格式化字符串时才使用stringWithFormat:。不需要将字符串分配给字符串变量。

关于ios - NSFileManager不保存数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17605351/

10-16 17:02
查看更多