我在我的非 arc 项目中使用了 apple 的 Reachabily 类。当我用仪器运行它来查找内存泄漏时,它指的是可达性方法。这是问题所在:
+ (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)hostAddress);
WReachability* returnValue = NULL;
if (reachability != NULL)
{
returnValue = [[self alloc] init];
if (returnValue != NULL)
{
returnValue->reachabilityRef = reachability;
returnValue->localWiFiRef = NO;
}
}
return returnValue;
}
泄露的对象是reachability和returnValue。 我知道 SCNetworkReachabilityCreateWithAddress 创建了一个新实例,我必须 CFRelease 它,但它发生在 dealloc 中!
- (void)dealloc
{
[self stopNotifier];
if (reachabilityRef != NULL)
{
CFRelease(reachabilityRef);
}
[super dealloc];
}
那么我该怎么做才能避免内存泄漏呢?
更新: 也许问题在于如何调用可达性?我使用这种方法:
+ (instancetype)reachabilityForInternetConnection;
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
return [self reachabilityWithAddress:&zeroAddress];
}
然后我这样调用 Reachability:
[[Reachability reachabilityForInternetConnection] startNotifier];
并且不要将其分配给任何对象,只需使用这一行即可。 我试图将此调用更改为:
Reachability *reachability = [[Reachability reachabilityForInternetConnection] autorelease];
[reachability startNotifier];
但是在这个分析器告诉我“自动释放太多”之后。
最佳答案
@Alexart 的回答对我有用,但如果你想要一个简化版本,请使用
+(instancetype)reachabilityWithAddress:(void *)hostAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
if (ref)
{
id reachability = [[self alloc] initWithReachabilityRef:CFBridgingRetain((__bridge id)ref)];
CFRelease(ref);
return reachability;
}
return nil;
关于ios - Apple 的可达性内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20652033/