objective c - iOS How to check if valueForKey exist or not? -
i have question checking existence of valueforkey. here's code:
id _jsonid = [nsjsonserialization jsonobjectwithdata:[_json datausingencoding:nsutf8stringencoding] options:0 error:&_error]; monday = [[nsmutablearray alloc] init]; if ([_jsonid valueforkey:@"mon"]!= nil) { _keymon = [_jsonid valueforkey:@"mon"]; [monday addobject:@"monday"]; (int i=0; i<5; i++) { if ([_keymon objectatindex:i]!=[nsnull null]) { [monday addobject:[_keymon objectatindex:i]]; } } } else { [_keytues addobject:@"no class today"]; [monday addobject:[_keymon objectatindex:1]]; }
the idea is, if _jsonid valueforkey
came nothing, can add nsstringaddobject:@"no class today
incase xcode tells me that: *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** -[__nsarraym insertobject:atindex:]: object cannot nil'
like has been telling me now. have solution? tried if ([_jsonid valueforkey:@"mon"]!= nil)
didn't work. tried if ([_jsonid valueforkey:@"mon"]!= nil)
didn't work. tried if ([_jsonid valueforkey:@"mon"]!= (id)[nsnull null])
didn't work. tried if ([_jsonid valueforkey:@"mon"]!= [nsnull null)
didn't work.
i know _jsonid valueforkey
came pointer, have no idea how check if pointer null(or nil in objective-c if i'm correct). please me.
update: have tried using objectforkey , here code(_jsonid objectforkey nil, know try testing code)
if (_jsonid[@"sun"]== nil) { [_keysun addobject:@"no class today"]; [monday addobject:[_keysun objectatindex:1]]; } else{ _keysun = [_jsonid objectforkey:@"sun"]; [monday addobject:@"sunday"]; (int i=0; i<5; i++) { if ([_keysun objectatindex:i]!=nil) { [monday addobject:[_keysun objectatindex:i]]; } } }
still, xcode telling me i'm add nil nsarray.
*** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** -[__nsarraym insertobject:atindex:]: object cannot nil'
this driving me crazy...
i think figured out. let's @ code:
if (_jsonid[@"sun"]== nil) { [_keysun addobject:@"no class today"]; [monday addobject:[_keysun objectatindex:1]]; } else { _keysun = [_jsonid objectforkey:@"sun"]; ...
if there object key "sun" store _keysun. if there no object, store nothing _keysun. _keysun nil. send addobject message _keysun - message sent nil object nothing. call [_keysun objectatindex:1]. again, sending message nil object nothing, , returns nil, why add nil monday object , crash.
if had set _keysun empty nsmutablearray, have crashed reason: try add one object. can read 1 object objectatindex:0. read objectatindex:1 need two objects in array.
btw. [nsnull null] json parser if json document reading contains explicit null. if json contains "sun": null objectforkey:@"sun" give [nsnull null]. if json doesn't contain key "sun" @ all, objectforkey:@"sun" give nil.
Comments
Post a Comment