iphone - ios 应用程序内存不足

标签 iphone ios sdk

我正在开发一个从照片库导入照片的应用程序。导入照片时会占用大量内存,导入 160 张照片后会崩溃。

我不知道为什么会发生这种情况。任何帮助将不胜感激。

这是我的代码

- (void)agImagePickerController:(AGImagePickerController *)picker    didFinishPickingMediaWithInfo:(NSArray *)info{

[pickerView dismissViewControllerAnimated:YES completion:nil];
[self.navigationItem setHidesBackButton:YES];
[self.navigationItem.rightBarButtonItem setEnabled:NO];

MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText=@"Importing Your Photo(s)";



// USING GRAND CENTRAL DISPATCH

firstQueue=dispatch_queue_create("com.import.photos", nil);
dispatch_async(firstQueue, ^{

    [self beingBackgroundUpdateTask];

    // Open connection
    //[albumObject openDB];


    // Start the loop from here ******************************************************
    int j=0;
    for(j=0;j<info.count;j++){

        // update the hud label
        hud.labelText=[[NSString alloc] initWithFormat:@"Importing %i of %i",j+1, [info  count]];


        // Create new image from returned array
        ALAssetRepresentation *rep = [[info objectAtIndex: j] defaultRepresentation];
        UIImage * image  = [UIImage imageWithCGImage:[rep fullScreenImage]];
        //rep=nil;

        // resize the image for the thumbnail and save it in new image
        UIImage *newImage=[image  resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(75, 75)  interpolationQuality:kCGInterpolationDefault];


        NSDate *date = [NSDate date];

        NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"DD_MM_YY_HH_mm_ss"];
        NSString *dateString = [dateFormat stringFromDate:date];

        int random=rand();
        // create new file names
        NSString *fileName=[[NSString alloc] initWithFormat:@"%d%@",random,dateString];
        NSString *s_fileName=[[NSString alloc]  initWithFormat:@"small_%d%@",random,dateString];
        // where to save this image
        NSString *imagePath=[self.documentsDirectory  stringByAppendingPathComponent:fileName];
        NSString *s_imagePath=[self.documentsDirectory stringByAppendingPathComponent:s_fileName];


        NSLog(@"type: %@",[rep.url pathExtension]);

        if ([[rep.url pathExtension] isEqualToString:@"JPG"]) {
            // its jpg
            NSData *rawImage=UIImageJPEGRepresentation(image, 1.0);
            NSData *thumb=UIImageJPEGRepresentation(newImage, 1.0);


            image=nil;
            newImage=nil;
            date=nil;
            dateFormat=nil;
            dateString=nil;
            random=nil;

            // Create the images
            [rawImage writeToFile:imagePath atomically:YES];
            [thumb writeToFile:s_imagePath atomically:YES];

            imagePath=nil;
            s_imagePath=nil;
            rawImage=nil;
            thumb=nil;

        }

        if ([[rep.url pathExtension] isEqualToString:@"PNG"]) {
            // its PNG
            // save it in NSData to it can be saved in the directory
            NSData *rawImage=UIImagePNGRepresentation(image);
            NSData *thumb=UIImagePNGRepresentation(newImage);




            image=nil;
            newImage=nil;
            date=nil;
            dateFormat=nil;
            dateString=nil;
            random=nil;

            // Create the images
            [rawImage writeToFile:imagePath atomically:YES];
            [thumb writeToFile:s_imagePath atomically:YES];

            imagePath=nil;
            s_imagePath=nil;
            rawImage=nil;
            thumb=nil;

        }





        // Now save it to database


        [albumObject savePhoto:fileName toFID:PassedID toName:s_fileName  albumName:singletonObj.currentAlbum photosName:singletonObj.currentPhotos];


        [display_photos addObject:[MWPhoto photoWithFilePath:[self.documentsDirectory  stringByAppendingPathComponent:fileName]]];

        UIImage *img=[UIImage imageWithContentsOfFile:[self.documentsDirectory  stringByAppendingPathComponent:s_fileName]];

        [collection_photos addObject:img];

        img=nil;

        NSArray *pObj=[[NSArray alloc] initWithObjects:fileName,s_fileName, nil];
        [photos addObject:pObj];

        pObj=nil;
        fileName=nil;

        s_fileName=nil;


    } j=nil;

    // Update the album photo count to reflect the changes
    [albumObject updateAlbumCount:PassedID photocount:[photos count]  albumName:singletonObj.currentAlbum];
    photos=[albumObject getPhotos:PassedID photosName:singletonObj.currentPhotos];

    // End the loop here ***************************************************************

    dispatch_async(dispatch_get_main_queue(), ^{
    [self.collectionView reloadData];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.navigationItem setHidesBackButton:NO];
    [self.navigationItem.rightBarButtonItem setEnabled:YES];

    });

    });



}

最佳答案

在循环中,会生成很多额外的对象,直到整个循环结束后它们才会被释放。但它永远不会完成,因为额外的对象会不断堆积,直到内存耗尽。第一道防线是将循环内部包装在 @autoreleasepool block 中。

举个例子,看看我书中的这一部分:http://www.apeth.com/iOSBook/ch12.html#_autorelease向下滚动到该部分的底部。

for /* loop iterator goes here */ {
    @autoreleasepool {
        // everything inside the for loop goes here
    }
}

编辑:我有另一个建议:你最终会得到一系列图像或类似的东西吗?我不太清楚。如果是这样,那么不要将图像存储在内存中作为这一切的最终结果,而是将图像保留在磁盘上并存储它们的 URL 或文件路径。这样,您仅在需要时才获取图像。图像在内存中占用大量空间,并且随着大小呈指数级增长。

关于iphone - ios 应用程序内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16254695/

相关文章:

iphone - 保存用户默认值时出现随机 BAD ACCESS

iphone - 处理 UIViewController 中的粘贴事件

ios - 无法将类型 'UITableViewCell' (0x10c111c68) 的值转换为子类

Android - 从 Facebook 获取个人资料封面图片

ios - UITableViewCell 图像从 url 加载

iphone - 在 iphone 中使用 Brautaset Json 框架时出错

ios - zxing 专注于 iOS

iphone - 设置特定日期的任务(iOS 应用程序)

火狐扩展 SDK : how to access address bar

ipad - 如何使用 Storyboard在 4.2 Xcode 中创建自定义模态转场