如何减少CPU内存使用量?

时间:2016-06-11 13:39:30

标签: ios objective-c xcode xcode7

我正在处理上传图片应用程序,这似乎对我来说很好。我正在上传100张图片。当我运行这个过程4-5次应用程序崩溃。

这在我看来是内存使用问题。如何减少内存。我不希望我的应用程序崩溃。

 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];
                                       }
                                   });
                }
            }
        }
    });

请告诉我。

1 个答案:

答案 0 :(得分:2)

确保您考虑代码,以便将图像加载到内存中,上传,然后释放它。不要一次在内存中构建所有图像的数组。

如果你这样做了,你可能仍然会有自动释放问题。

您可以尝试在循环中添加自动发布池:

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

但是,在发布代码之前,提供更具体的帮助有点困难。

修改

您正在使用NSURLConnection。该类已被弃用。请改用NSURLSession。这不是你问题的原因。问题的原因是你正在排队100个连接,所有数据都在内存中。

您应该使用NSURLSession和上传任务。使用上传任务,您只需提供文件的URL,系统就会为您上传(并为您管理内存。)