保存在应用程序中拍摄的照片并使用核心数据

时间:2013-06-27 23:30:45

标签: ios objective-c image uiimagepickercontroller save

我正在使用核心数据来保存我的应用程序中包含的一组图像的文件名。

 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
    // app already launched
}
else
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    // This is the first launch ever
        NSArray *mainDishImages = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"full_breakfast.jpg", @"ham_and_cheese_panini.jpg", @"ham_and_egg_sandwich.jpg", @"hamburger.jpg", @"instant_noodle_with_egg.jpg", @"japanese_noodle_with_pork.jpg", @"mushroom_risotto.jpg", @"noodle_with_bbq_pork.jpg", @"thai_shrimp_cake.jpg", @"vegetable_curry.jpg", nil];
        NSArray *drinkDessertImages = [NSArray arrayWithObjects:@"angry_birds_cake.jpg", @"creme_brelee.jpg", @"green_tea.jpg", @"starbucks_coffee.jpg", @"white_chocolate_donut.jpg", nil];
    for (NSString *imagePath in mainDishImages) {


    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:context];
        [newRecipe setValue:imagePath forKey:@"imageFilePath"];
    }
    for (NSString *imagePath in drinkDessertImages) {
        NSManagedObjectContext *context = [self managedObjectContext];
        NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:@"Deserts" inManagedObjectContext:context];
        [newRecipe setValue:imagePath forKey:@"imageFilePath"];
    }
}

但我也允许用户通过设备相机拍照来添加项目。如何保存图像以便我的应用程序可以再次使用它,并将其集成以使用我现有的核心数据方案?

由于

2 个答案:

答案 0 :(得分:2)

只需将新图像保存到用户文档文件夹,并将路径存储在核心数据中。存储名称为UUID的图像,使其唯一。

当您获取核心数据引用的图像时,请尝试使用imageNamed加载图像,如果它返回nil,请尝试以完整路径加载图像。


请参阅this answer关于UUID s。

有关文档文件夹的信息,请参阅this answer

答案 1 :(得分:1)

将图像作为数据下载后,请使用此方法将该图像存储在文档目录中。一旦下载完成每个图像,就将文件路径(代码块中提到的thumbNailAppFile)更新到您的实体中。希望这会帮助你。

 -(void *)writeDataAsFile:(NSData *)imageData
    {

        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSString * thumbNailFilename = [NSString stringWithFormat:@"%@%@.png",@"SomePrefixforimage",[self createUUID]];
        NSString * thumbNailAppFile = [documentsDirectory stringByAppendingPathComponent:thumbNailFilename];  // Image local path 

        [imageData writeToFile:thumbNailAppFile atomically:YES];

    }



- (NSString *)createUUID // Create Unique id for image name.
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}