2011-08-24 60 views
1

我有與無功的泄漏,我不知道如何解決它...SCNetworkReachabilityRef泄漏上的Xcode

下面的代碼:

bool success = false; 
    const char *host_name = [@"www.google.com" cStringUsingEncoding:NSASCIIStringEncoding]; 
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name); 
    SCNetworkReachabilityFlags flags; 
    success = SCNetworkReachabilityGetFlags(reachability, &flags); 
    bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
    !(flags & kSCNetworkFlagsConnectionRequired); 
    if (isAvailable) { 
     ... 
    }else{ 
     ... 
    } 
    CFRelease(reachability); 

泄漏:爲 90.5%線

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name); 

和該行9.5%:

success = SCNetworkReachabilityGetFlags(reachability, &flags); 

就是這樣。所以,如果你能幫助我,這可能是非常好的:D謝謝

回答

5

你實際上沒有泄漏。請注意,只有在您第一次調用API時,表面泄漏纔會發生?這只是背景設置,可以忽略。

但是,在使用Core Foundation和兼容類型時,您必須必須檢查NULL返回值。如果您通過NULLCFRelease(),您的應用將崩潰。所以,你必須此:

bool success = false; 
const char *host_name = [@"www.google.com" cStringUsingEncoding:NSASCIIStringEncoding]; 
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name); 
if (reachability) { 
    SCNetworkReachabilityFlags flags; 
    success = SCNetworkReachabilityGetFlags(reachability, &flags); 
    bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
    !(flags & kSCNetworkFlagsConnectionRequired); 
    if (isAvailable) { 
     ... 
    }else{ 
     ... 
    } 
    CFRelease(reachability); 
} 

注意添加if聲明。