无法从本地设备中保存的文件加载数据

时间:2015-03-31 18:07:56

标签: ios core-data

这应该是超级简单但不知何故我无法理解。

我有一个图像,我在设备中本地保存,我正在使用Core Data存储文件保存位置。核心数据不是保存文件本身,而是保存位置。

我这样做:

- (NSString *) saveFileToLocalFilePath
{
    card_FileName = [NSString stringWithFormat:@"%@_%@.png",
                     self.card_name,
                     self.card_issuer];

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                        NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    path = [path stringByAppendingString:@"/"];
    path = [path stringByAppendingString:card_FileName];

    [UIImagePNGRepresentation(imageTaken) writeToFile:path atomically:YES];

    return path;
}

- (void) generateNewCoreDataCardWithFilePath:(NSString *)filePath
{
    Card *card = (Card *) [NSEntityDescription insertNewObjectForEntityForName:@"Card"
                                                        inManagedObjectContext:[CoreDataHelper getManagedObjectContext]];
    card.card_name = self.card_name;
    card.card_issuer = self.card_issuer;
    card.card_type = self.card_type;
    card.card_image_location = card_FileName; // this should just be the "DefaultCardName_DefaultCardIssuer.png" part
}

然后将文件保存到此位置:

/var/mobile/Containers/Data/Application/E02566CA-B992-41AE-9B47-51903448015E/Documents/DefaultCardName_DefaultCardIssuer.png

我相信这一部分有效。我遇到的问题是检索文件。 这是我正在做的打开文件:

Card *card = [[self fetchedResultsController]objectAtIndexPath:indexPath];

NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
                                    NSDocumentDirectory,
                                    NSUserDomainMask,
                                    YES);
NSString *path = [arrayPaths objectAtIndex:0];
path = [path stringByAppendingString:@"/"];
path = [path stringByAppendingString:card.card_image_location];

NSData *data = [NSData dataWithContentsOfFile:path];

问题是数据每次都返回零。

有关我做错的任何建议吗? 谢谢!

修改 通过使用:

改变我调用数据的方式来实现它
[NSData dataWithContentsOfFile:filePath]

1 个答案:

答案 0 :(得分:0)

请问您是否可以使用以下代码测试文件是否实际保存?

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"card.card_image_location"];
BOOL fileExists = [fileManager fileExistsAtPath:filePath];