因此,我構建了一個應用程序,用戶可以自己拍攝照片,並將它們保存到相機膠捲中,然後保存對資產URL的引用以在應用程序中顯示它們。起初這種模式似乎工作得很好,但隨着我拍攝越來越多的照片,它開始接受記憶警告並最終墜毀。有沒有更好的方法來解決這個問題?優化一系列UIImages
這是我如何加載了保存的照片在推出應用程序的(其中凍結長達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");
}
}];
}
啓用了烏爾項目ARC .. BCZ我沒有看到任何手動釋放/自動釋放池在我們的代碼... –
@iOSCoder是它 – Chris
看看這個.. HTTP:/? /stackoverflow.com/questions/9973259/what-is-the-correct-way-to-import-save-photos-from-iphone-album –