2011-12-16 74 views
2

将图像与Core Data一起使用不成问题。有很多关于如何做这样的例子:How should I store UIImages within my Core Data database?如何使用Core Data和RestKit来映射和存储图像?

我想知道如何使用RestKit下载图像并将它们正确映射到Core Data。有关于如何上传图像但不下载和检索的RestKit示例。

现在我的实体只有一个图像的url属性,但我希望能够离线访问图像。我正在考虑做一些简单的映射,比如下载图像并将其重命名为它所属的对象的ID,但是在我重新创建这个轮子之前,我想知道是否有其他人知道实现这个最“正确”的方法。

+0

你的目标部署是10.7和iOS 5? – user170317 2011-12-17 09:19:27

+0

这个项目的iOS5,但它也将有助于4.0 – 2011-12-17 20:52:53

回答

1

最后我只是请求与图像URL和接收我抢了图像的URL将其设置为我的对象的图像属性的对象之后的对象。简单

NSURL * imageURL; UIImage * selectedImage;

for (Employee *employee in _employees){ 

     imageURL = [NSURL URLWithString:employee.imageURL]; 
     selectedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]]; 
     // Delete any existing image. 
     NSManagedObject *oldImage = employee.image; 
     if (oldImage != nil) { 
      [employee.managedObjectContext deleteObject:oldImage]; 
     } 

     // Create an image object for the new image. 
     NSManagedObject *image = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:employee.managedObjectContext]; 
     employee.image = image; 

     // Set the image for the image managed object. 
     [image setValue:selectedImage forKey:@"image"]; 

     // Create a thumbnail version of the image for the recipe object. 
     CGSize size = selectedImage.size; 
     CGFloat ratio = 0; 
     if (size.width > size.height) { 
      ratio = 100.0/size.width; 
     } else { 
      ratio = 100.0/size.height; 
     } 
     CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height); 

     UIGraphicsBeginImageContext(rect.size); 
     [selectedImage drawInRect:rect]; 
     employee.thumbnailImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    }