如何在iOS中解决此警告?内存泄漏

时间:2014-03-24 17:49:58

标签: ios memory memory-leaks warnings

该函数中的这一行会产生一个警告: PerformSelector可能会导致内存泄漏,因为它的选择器未知。我做错了什么?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

[_delegate1 performSelector:_selector1 withObject:json];

}

以下是方法performSelector

- (void)HttpRequest:(NSURL*)url PostString:(NSString *)poststring method:(int)method withselector:(SEL)selector withdelegate:(id)delegate
{    

 _responseData = [[NSMutableData alloc] init];
// procedures for parse at desired URL
request = [NSMutableURLRequest requestWithURL:url
                                  cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                              timeoutInterval:5];

// set HTTP method
if (method == 0) {
    [request setHTTPMethod:@"GET"];
    // asks xml response
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; }

_selector1 = selector ;
_delegate1 = delegate ;

[self startConnection];

return;
}

1 个答案:

答案 0 :(得分:1)

你没有做错任何事。编译器会引发警告,因为它还不知道选择器。 如果有一个地方您收到此警告,请使用

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
       [_delegate1 performSelector:_selector1 withObject:json];
#pragma clang diagnostic pop

如果有多个地方您可以定义宏

#define SuppressPerformSelectorLeakWarning(Stuff) \
    do { \
        _Pragma("clang diagnostic push") \
        _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
        Stuff; \
        _Pragma("clang diagnostic pop") \
    } while (0)

然后在发生警告的所有地方使用宏

SuppressPerformSelectorLeakWarning(

   [_delegate1 performSelector:_selector1 withObject:json];
);

调用这样的每个选择器,它会抑制警告