0

所以我正在构建一个用户为自己拍照的应用程序,它将它们保存到相机胶卷中,并且我正在保存对资产 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");
        }

    }];

}
4

1 回答 1

2

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

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

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

于 2013-08-20T03:44:04.870 回答