ios - Apple 的可达性内存泄漏

标签 ios objective-c xcode memory-leaks reachability

我在我的非 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/

相关文章:

objective-c - 倒计时器

xcode - ffmpeg : Is this a bug in Xcode?

ios - 如何避免在 iOS 中使用 Unity MovePlayerOnYAxis 时出现延迟?

ios - 如何在tableview中显示字典数据

iphone - 当我调用 [Timer isValid] 或 [Timer invalidate] 时,NSTimer 崩溃

ios - 使用函数重新加载表/数组?

ios - Podfile 包含框架或静态库目标,Podfile 不包含主机目标

ios - 水平ScrollView停在中间

ios - http响应回调后移动到另一个ViewController

ios - 需要有关亚马逊示例项目的帮助