I have a code for retriving remote json file. I tried to print the error when the network is not available (turing on airplane mode on purpose to produce the error).
But every time, it raised a EXE_BAD_ACCESS on the logging line
My code is like this:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if(error != nil){
let errorDesc = error!.description ?? ""
NSLog("HTTP request error = \(error!.code), desc = \(errorDesc)")
handler(houseList, error)
return
}
...Omitted for Brevity...
}
NSLog("HTTP request error = \(error!.code), desc = \(errorDesc)")
is the line that raised the error
My Observations:
First of all, in my debug window the error.description
looks
perfectly fine. i can see the data with no problems.
Secondly, if i change NSLog to print()
, then everything works just
fine!
Lastly, if I change the original line to the following, it works too
NSLog("HTTP request error = (error!.code), desc = %@", errorDesc)
Is it because NSlog cannot process String Interpolation correctly?
If this is the case, then why in some cases such as "HTTP request error = \(error!.code)
, it can work ?
My Dev Environment: Xcode: Version 7.0.1 (7A1001) OS X: Yosemite 10.10.5(14F27
Thank you for your time!! :)
The first argument of NSLog()
is a format string, similar as in
the printf()
function from the C library. This format string serves
as a template and contains format specifiers
such as %d
, %s
, %@
, ... The format specifies how the
remaining arguments are interpreted.
Now in your case, in
NSLog("HTTP request error = \(error!.code), desc = \(errorDesc)")
the error code and description are interpolated into the format string.
If the error descriptions happens to contain a format specifier (e.g. %s
) then NSLog()
expects another argument (e.g. string).
If there is no argument or if it has the wrong type, the behavior is
undefined and the code may crash.
Therefore, the format string should always be a constant string literal:
NSLog("HTTP request error = %ld, desc = %@", error!.code, errorDesc)
If you want to take advantage of the Swift string interpolation
then use just %@
as the format and pass the interpolated String
as additional argument:
NSLog("%@", "HTTP request error = \(error!.code), desc = \(errorDesc)")