objective c - NSDate's initWithString: is returning nil -
i'm using stig brautaset's json framework serialize objects, including nsdates (which not directly supported).
i decided use nsdate's description jsonfragment representation of date (i don't care minor loss of precision incurred in doing so).
to extend stig brautaset's json framework include nsdates, defined category:
@interface nsdate (nsdate_json) <jsoninitializer> -(nsstring *) jsonfragment; @end
to recreate nsdate (and other classes) json, defined protocol following initializer:
@protocol jsoninitializer <nsobject> -(id) initwithjsonrepresentation: (nsstring *) ajsonrepresentation; @end
i'm having issues initializer. in nsdate's case, calls initwithstring:, , that's trouble: returns nil. implementation:
#import "nsdate+json.h" @implementation nsdate (nsdate_json) -(nsstring *) jsonfragment{ nsstring *strrepr = [self description]; return [strrepr jsonfragment]; } -(id) initwithjsonrepresentation:(nsstring *)ajsonrepresentation{ return [self initwithstring: ajsonrepresentation]; //returns nil! } @end
i'm not sure what's going on. besides, compiler warns me initwithstring: method in initwithjsonrepresentation: not found.
anybody knows might going on?
the full source code test case available here.
your test program is:
nsdate *d1 = [[[nsdate alloc] init] autorelease]; nsstring *repr = [d1 jsonfragment]; nsdate *dd = [[[nsdate alloc] initwithstring:[d1 description]] autorelease ]; nsdate *d2 = [[[nsdate alloc] initwithjsonrepresentation:repr] autorelease];
your -jsonfragment
category method is:
-(nsstring *) jsonfragment{ nsstring *strrepr = [self description]; return [strrepr jsonfragment]; }
what’s happening in method obtain string representation of date using -description
, , json representation of string using -jsonfragment
.
in sbjson, -jsonfragment
returns representation of given object json data. json specification requires strings quoted. in program:
nsstring *repr = [d1 jsonfragment];
repr
contains string @"\"2011-04-29 10:20:30 -0600\""
. because of quotes, string not valid string used -[nsdate initwithstring:]
.
if change:
nsstring *repr = [d1 jsonfragment];
to:
nsstring *repr = [[d1 jsonfragment] jsonfragmentvalue];
so sbjson parses fragment , returns string without quotes, should work.
Comments
Post a Comment