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/

相关文章:

ios - react-native iOS新方案报错: Undefined symbol: _OBJC_CLASS_$_FlipperClient

iOS xcode 麦克风音量检测?

ios - 具有自动调整大小的 insertRowsAtIndexPaths 的 UITableView 更改 contentOffset

ios - 将 UIView 定位在点击点以启动弹出窗口

objective-c - 我可以使用协议(protocol)对象作为 NSDictionary 中的键吗?

iphone - 文本字段数组边界之外的 UIAlertView 错误但未使用文本字段

javascript - 使用 Apache Cordova for Visual Studio 进行身份验证

android - 使用 phonegap 获取应用程序的热图分析数据

ios - 如何获得一个按钮来确定要转到哪个 View Controller ?

ios - UIButton 高度为 0 但标题仍然可见