简体   繁体   English

如何减少CPU内存使用量?

[英]How to reduce CPU Memory usage?

I am working on upload images application which seems working fine for me. 我正在上载图片应用程序,对我来说似乎很好。 I am uploading 100 images. 我正在上传100张图片。 and when i run this process 4-5 times application crashes out. 当我运行此过程4-5次时,应用程序崩溃了。

This seems to me memory usage issue.. How to reduce that memory. 在我看来这是内存使用问题。如何减少该内存。 I don't want to my application get crashed. 我不想让我的应用程序崩溃。

 btn_Cancel.userInteractionEnabled=NO;
    btn_Share.userInteractionEnabled=NO;
    btn_Back.userInteractionEnabled=NO;
    btn_BackTransp.userInteractionEnabled=NO;
    btn_BareCode.userInteractionEnabled=NO;

    [self integratedLoaderView];



    NSURL *url=[NSURL URLWithString:@"http:/apiurl /"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
        NSString *str_EstimateNumber=[NSString stringWithFormat:@"%@",txtFld_FolderName.text];
        NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
        formatter.dateFormat=@"yyyy-MM-dd";
        string=[formatter stringFromDate:[NSDate date]];
        NSString *str_time;
        formatter.dateFormat=@"hh.mm.ss a";
        str_time=[formatter stringFromDate:[NSDate date]];
        NSString *str_AppendString=[NSString stringWithFormat:@"%@ at %@",string,str_time];
        NSInteger str_Counter=[[NSString stringWithFormat:@"%lu",(unsigned long)[delegate.ary_ImageData count]] integerValue];
        NSString *str_Value=[NSString stringWithFormat:@"%ld",(long)str_Counter];
        NSString *str_Username=[NSString stringWithFormat:@"%@/Images",txtFld_SelectedFTP.text];
        abc=0;
        for (int i=0;i<[ary_Tosend count]; i++)
        {

            sleep(0.6);

            abc++;
            if ([str_ConnectionStatus isEqualToString:@"WiFi"])
            {
            }
            if ([str_ConnectionStatus isEqualToString:@"Cellular"])
            {
            }
            if ([str_ConnectionStatus isEqualToString:@"No Connection"])
            {
                btn_Cancel.userInteractionEnabled=YES;
                btn_Share.userInteractionEnabled=YES;
                btn_Back.userInteractionEnabled=YES;
                btn_BackTransp.userInteractionEnabled=YES;
                btn_BareCode.userInteractionEnabled=YES;
                NSString *str_Total=[NSString stringWithFormat:@"%lu",(unsigned long)[ary_Tosend count]];
                NSString *str_Saved=[NSString stringWithFormat:@"%lu",(unsigned long)[delegate.ary_ImageData count]];
                NSInteger total_Count=[str_Total integerValue]-[str_Saved integerValue];

                [self saveInDBWhenConnectionLost:total_Count];

                [self ShowAlertForCheckInternetConnection];
                return ;
            }
            if ([str_ConnectionStatus isEqualToString:@""])
            {
                btn_Cancel.userInteractionEnabled=YES;
                btn_Share.userInteractionEnabled=YES;
                btn_Back.userInteractionEnabled=YES;
                btn_BackTransp.userInteractionEnabled=YES;
                btn_BareCode.userInteractionEnabled=YES;
                NSString *str_Total=[NSString stringWithFormat:@"%lu",(unsigned long)[ary_Tosend count]];
                NSString *str_Saved=[NSString stringWithFormat:@"%lu",(unsigned long)[delegate.ary_ImageData count]];
                NSInteger total_Count=[str_Total integerValue]-[str_Saved integerValue];

                [self saveInDBWhenConnectionLost:total_Count];
                [self ShowAlertForCheckInternetConnection];

                return ;
            }

            NSString *str_fileName;
            str_fileName=[NSString stringWithFormat:@"%@_%@ %i.jpg",str_EstimateNumber,str_AppendString,abc];
            NSDictionary *params=nil;
            NSData *imageToUpload=UIImageJPEGRepresentation([ary_Tosend objectAtIndex:i],0.25);
            NSString *encodedString=[NSString stringWithFormat:@"%@",[imageToUpload base64Encoding]];

            params= @{
                     @"categoryName" :txtFld_Category.text,
                     @"folderName"   :txtFld_FolderName.text,
                     @"fileName"     :str_fileName,
                     @"userName"     :str_Username,
                     @"postedFile"   :encodedString,
                     @"accessToken" :@"Q)4%v59!@lyr"
                     };

            AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
            httpClient.parameterEncoding = AFFormURLParameterEncoding;
            [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
            [httpClient setDefaultHeader:@"Accept" value:@"application/json"];
            NSMutableURLRequest *request=[httpClient requestWithMethod:@"POST"
                                                                  path:@"UploadImages/upload"
                                                            parameters:params];

            NSURLResponse* response=nil;
            NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
            if(data.length)
            {
                NSString *responseString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSError *error = nil;
                NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

                if(responseString && responseString.length)
                {
                    [delegate.ary_GetUploadedCount addObject:JSON];
                    [self responseUpload:JSON];
                    dispatch_async(dispatch_get_main_queue(),
                                   ^{
                                       if(i < delegate.ary_ImageData. count)
                                       {
                                           [delegate.ary_ImageData removeObjectAtIndex:i];
                                           [delegate.ary_TotalImages removeObjectAtIndex:i];
                                           [ary_DataToConvert removeObjectAtIndex:i];
                                           [ary_DataToConvert1 removeObjectAtIndex:i];

                                           NSUserDefaults *default_AllImg=[NSUserDefaults standardUserDefaults];
                                           [default_AllImg setValue:ary_DataToConvert forKey:@"ImageDetail"];
                                           [default_AllImg synchronize];

                                           NSUserDefaults *default_AllImg1=[NSUserDefaults standardUserDefaults];
                                           [default_AllImg1 setValue:ary_DataToConvert1 forKey:@"ImageData"];
                                           [default_AllImg1 synchronize];
                                       }
                                   });
                }
            }
        }
    });

Please tell me. 请告诉我。

Make sure you factor your code so that you load an image into memory, upload it, and then release it. 确保对代码进行分解,以便将图像加载到内存中,然后上传并释放。 Don't build an array of all the images in memory at once. 不要一次在内存中构建所有图像的数组。

If you've done that you might still have an autorelease problem. 如果这样做,您可能仍然会遇到自动发布问题。

You might try adding an auto release pool inside your loop: 您可以尝试在循环中添加自动释放池:

for (NSString *filename in filenames)
{
  @autoreleasepool
  {
    //Your code to load an image and upload it to the server goes here
  }
}

However, it's a bit hard to give more specific help until you post your code. 但是,在发布代码之前,要提供更具体的帮助有些困难。

EDIT 编辑

You are using NSURLConnection . 您正在使用NSURLConnection That class has been deprecated. 该类已被弃用。 Use NSURLSession instead. 请改用NSURLSession That's not the cause of your problem. 那不是你问题的原因。 The cause of your problem is that your are queuing up 100 connections at the same time, with all of their data in memory. 问题的原因是您正在同时排队100个连接,并将所有数据存储在内存中。

You should use NSURLSession and an upload task. 您应该使用NSURLSession和一个上传任务。 With an upload task you just provide a URL to the file and the system takes care of uploading it for you (and manages the memory for you.) 使用上传任务,您只需提供文件的URL,系统便会为您上传文件(并为您管理内存)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM