ios - 当图像保存在核心数据的 Collection View 中时,应用程序因内存错误而崩溃

标签 ios objective-c xcode core-data uicollectionview

我正在将图像添加到核心数据的 Collection View 中,该核心数据从 uiimagepicker 获取图像。但是,当我将 6 张以上的图像加载到我的应用程序时,它会占用大部分内存,有时还会崩溃。除了获取图像并将它们直接放入具有 100x100 ImageView 的单元格中的 Collection View 之外,我没有对图像执行任何操作。有谁知道我可以做些什么来减少内存并使应用程序不崩溃?

代码片段:

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _fetchedObjects.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        PhotosCollectionViewCell * cell = (PhotosCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"photoCell" forIndexPath:indexPath];
        NSManagedObject *object = [_fetchedObjects objectAtIndex:indexPath.row];
        cell.cellImage.image = [UIImage imageWithData:[object valueForKey:@"image"]];
        return cell;
}

其他类:

    Photo * photoEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:_context];
    NSError * error;
    NSData *imageData = UIImagePNGRepresentation(_image);
    photoEntity.name = _nameField.text;
    photoEntity.image = imageData;
    photoEntity.imagedescription = _descriptionField.text;
    if (![_context save:&error]) {
        NSLog(@"There was a save error:%@",error);
    }
    [self dismissViewControllerAnimated:YES completion:nil];

谢谢

最佳答案

不要在 Core Data 中存储图像。它们占用太多内存!如果将其属性之一是图像的对象读入内存,则将该图像读入内存。因此,如果您有 100 个对象并获取它们的名称,那么您还会将 100 张图像加载到内存中,这可能会终止您的应用程序。

在 Core Data 中,存储对图像的引用。将实际图像存储在其他地方,例如在磁盘上。

关于ios - 当图像保存在核心数据的 Collection View 中时,应用程序因内存错误而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21226102/

相关文章:

ios - 当 Xamarin.iOS 中显示软件键盘时如何向上移动布局

iphone - 我应该在 viewDidUnload 和 dealloc 中注销 NSNotification 吗?

ios - CareKit 和 ResearchKit 冲突

objective-c - 如果 drawRect 被覆盖,iOS subview 显示为黑色矩形

objective-c - 如何在 Objective-C 中检测未使用的方法和#import

ios - Xcode 10 "Could not build module Darwin/Foundation/CoreFoundation"等

iphone - Xcode源码自动格式化

ios - uinavigationbar细线颜色怎么修改

iphone - 将 NIB 文件加载到 UIView 时遇到问题

ios - 从 NSDictionary Swift 设置枚举