AFNetworking code giving me Memory Leaks

2019-08-06 17:25发布

@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条回答
做自己的国王
2楼-- · 2019-08-06 18:03

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%
}
查看更多
登录 后发表回答