2013-06-27 71 views
1

我使用的核心数据,保存文件名的一组图像的核心数据包括在我的应用程序。保存在应用拍摄的照片,并使用

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"]; 
    } 
} 

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

感谢

+0

你所需要的全分辨率图像?例如,在我正在开发的应用程序中,我需要图像,但我不需要更高的分辨率,因此我将它们作为压缩图像(jpeg)存储在Core Data中。它运作良好,我不必处理外部参考。如果您必须具有完整的分辨率,那么您几乎需要将其存储在文件系统中并参考它。 – RegularExpression

+0

保存完整的分辨率将是优惠的,因为应用程序将允许用户稍后将immage上传到Facebook,并且还将调整图像大小以用于UICollectionView和详细视图。 – Andrewp97

回答

2

新的图像就保存到用户的文档文件夹,存储核心数据的路径。用UUID这个名字存储图像,使其具有独特性。

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


this answerUUID秒。

this answer有关的文件的文件夹。

+0

谢谢,您如何将内容保存到用户文档文件夹以及什么是UUID? – Andrewp97

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]; 
} 
相关问题