Thursday, 15 September 2011

ios - Why didn't JSON parser catch non-validated data? -



ios - Why didn't JSON parser catch non-validated data? -

once & awhile fatal crash: exc_bad_instruction.

this can happen after few iterations.

i've traced source of crash (what believe be) nsjsonserialization parser happens non-validated string --> data.

that is, works few iterations (exit, relaunch app & run again); crashes. clear simulator & rebuild... pattern repeats.

found out doing println(string) before json call; , did cut/paste of string json validator , found errant '(' at beginning:

({"photos":{"page":1,"pages":1340,.....

here's actual screen dump:

question: why didn't json parser trap error within nserror vs throwing fatal exception? ...is bug?

you're forcibly unwrapping object returned nsjsonserialization.jsonobjectwithdata(), nil if parser error occurs. when happens, crash runtime error.

since don't @ contents of jsonerror @ all, can ignore error parameter , utilize optional binding instead; e.g.

if allow jsondict = nsjsonserialization.jsonobjectwithdata(data!, options: .allowfragments, error: nil) nsdictionary { // jsondict } else { println("error") homecoming }

if want inspect error object, write this:

let jsondict = nsjsonserialization.jsonobjectwithdata(data!, options: .allowfragments, error: &jsonerror) nsdictionary? if jsondict == nil { if allow err = jsonerror { println(err.localizeddescription) } homecoming } // jsondict

ios json swift error-handling runtime-error

No comments:

Post a Comment