AFNetworking code giving me Memory Leaks

梦想与她 提交于 2020-01-05 17:49:19

问题


@implementation GetData

static NSString *string = @"https://afternoon-springs-7986.herokuapp.com/";
static NSString *baseStr = @"https://afternoon-springs-7986.herokuapp.com/updateInformation";    

-(void) postEventInfo: (NSDictionary *) eventInfoObject


    {
        NSURL *url = [NSURL URLWithString:string];  // 6.5%
       // NSURL *baseURL = [NSURL URLWithString:@"http://localhost:5000/"];

        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        UIView *topView = window.rootViewController.view;

        self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url]; // 71%
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; // 9.7%

        [self.manager POST:@"/addEvent/" parameters:eventInfoObject success:^(NSURLSessionDataTask *task, id responseObject) { // 12.9%

        [FVCustomAlertView showDefaultDoneAlertOnView:topView withTitle:@"Klart!"];

        } failure:^(NSURLSessionDataTask *task, NSError *error) {

        [FVCustomAlertView showDefaultErrorAlertOnView:topView withTitle:@"Ett fel uppstod, försök igen!"];
        }];
    }

I am receiving memory leaks on this code above. As you can see i commented the amount of % same as the Leaks instrument did. Im running Xcode 6, and the test is made on my iPhone device 5s IOS 7.1.1

Here is a screenshot of how to leaks tool was looking like. https://www.dropbox.com/s/beh4no79wgk54bm/Screen%20Shot%202015-03-12%20at%2013.09.53.png?dl=0


回答1:


Every time you call "postEventInfo", you're creating a AFHTTPSessionManager object.

If you're using ARC, this should mean the old object gets released (i.e. not such a problem). But for best practices sake you should do something like this:

// set self.manager only if it hasn't been created yet
if(!self.manager)
{
    self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url]; // 71%
    self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; // 9.7%
}


来源:https://stackoverflow.com/questions/29009469/afnetworking-code-giving-me-memory-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!