优化UIImages数组



所以我正在构建一个应用程序,用户可以拍摄自己的照片,它会将它们保存到相机胶卷中,我会保存对资产URL的引用,以便在应用程序中显示它们。起初,这个模型似乎运行良好,但随着我拍摄的照片越来越多,它开始收到内存警告,最终崩溃了。有没有更好的方法来解决这个问题?

这就是我在应用程序启动时加载保存的照片的方式(根据加载的照片数量,冻结应用程序最多10秒):

- (void) loadPhotosArray
{
    _photos = [[NSMutableArray alloc] init];
    NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey: @"savedImages"];
    if (data)
    {
        NSArray* storedUrls = [[NSArray alloc] initWithArray: [NSKeyedUnarchiver unarchiveObjectWithData: data]];
        // reverse array
        NSArray* urls = [[storedUrls reverseObjectEnumerator] allObjects];
        for (NSURL* assetUrl in urls)
        {
            // Block to handle image handling success
            ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
            {
                ALAssetRepresentation *rep = [myasset defaultRepresentation];
                CGImageRef iref = [rep fullResolutionImage];
                if (iref) {
                    UIImage* tempImage = [UIImage imageWithCGImage:iref];
                    UIImage* image = [[UIImage alloc] initWithCGImage: tempImage.CGImage scale: 1.0 orientation: UIImageOrientationRight];
                    // Set image in imageView
                    [_photos addObject: image];
                    [[NSNotificationCenter defaultCenter] postNotificationName: @"PhotosChanged" object: self];
                }
            };
            // Handles failure of getting image
            ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
            {
                NSLog(@"Can't get image - %@",[myerror localizedDescription]);
            };
            // Load image then call appropriate block
            ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
            [assetslibrary assetForURL: assetUrl
                           resultBlock: resultblock
                          failureBlock: failureblock];
        }
    }
    else
    {
        NSLog(@"Photo storage is empty");
    }
}

保存照片:

- (void) addImageToPhotos: (UIImage*)image
{
    // Store image at front of array
    NSMutableArray* temp = [[NSMutableArray alloc] initWithObjects: image, nil];
    // load rest of images onto temp array
    for (UIImage* image in _photos)
    {
        [temp addObject: image];
    }
    _photos = nil;
    _photos = [[NSMutableArray alloc] initWithArray: temp];
//    [self.photos addObject: image];
    [[NSNotificationCenter defaultCenter] postNotificationName: @"PhotosChanged" object: self.photos];
    // save to cache
    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library saveImage: image toAlbum: @kAlbumeName withCompletionBlock:^(NSError *error) {
        if (error)
        {
            NSLog(@"Error saving");
        }
    }];
}

我认为有两种方法可以优化这个问题。

  1. U应该只保存图像名称字符串,而不是保存UIImage对象,然后当需要显示图像时,根据保存的图像名称字符串使用分页来显示图像。

  2. U应该使用多线程来处理这个长时间的任务,建议U使用gcd来加载图像名称字符串。

最新更新