Reputation: 87
When calling setReachabilityStatusChangeBlock within a view controller, the following code throws an EXC_BAD_ACCESS exception. I'm pretty sure what is happening is that the self object is no longer referenced when the block is executed. What is the right way to provide a reference to self within the code block?
In the sample code below, commenting out the self.description code allows this to work. (Note: I'm on Xcode 6 beta 4)
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock{(status: AFNetworkReachabilityStatus?) in
switch status!.hashValue{
case AFNetworkReachabilityStatus.NotReachable.hashValue:
println("Not reachable")
case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue , AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue :
println("Reachable")
println(self.description) // Seems to cause error
default:
println("Unknown status")
}
}
Upvotes: 3
Views: 1172
Reputation: 12018
I had the exact same problem trying to use the AFNetworking reachability code from within a RestKit-based project. Apparently, as the OP notes, self is no longer available for reference when the block is executed. I had already set up my class that contains the reachability code as a singleton so instead of referencing self I referenced the singleton shared instance and it works.
Here is the singleton setup code:
class var sharedInstance: MyClass {
struct Static {
static let instance = MyClass()
}
return Static.instance
}
I can now reference the shared instance as:
MyClass.sharedInstance
So using that pattern you could update your block to be the following and it should work:
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock{(status: AFNetworkReachabilityStatus?) in
switch status!.hashValue{
case AFNetworkReachabilityStatus.NotReachable.hashValue:
println("Not reachable")
case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue , AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue :
println("Reachable")
println(MyClass.sharedInstance.description) // Seems to cause error
default:
println("Unknown status")
}
}
Upvotes: 3