ios - Is it ok not to invoke [super init] in a custom init method? -
i have mkpolyline
subblass want implement nscoding
, i.e.
@interface rsroutepolyline : mkpolyline <nscoding>
i asked question on best way encode c-array , got first-class answer. however, there no init method defined on mkpolyline
, i.e. there no other way give info other class method polylinewithpoints:points
.
is code comment ok?
- (void)encodewithcoder:(nscoder *)acoder { mkmappoint *points = self.points; nsuinteger pointcount = self.pointcount; nsdata *pointdata = [nsdata datawithbytes:points length:pointcount * sizeof(mkmappoint)]; [acoder encodeobject:pointdata forkey:@"points"]; [acoder encodeinteger:pointcount forkey:@"pointcount"]; } - (id)initwithcoder:(nscoder *)adecoder { nsdata* pointdata = [adecoder decodeobjectforkey:@"points"]; nsuinteger pointcount = [adecoder decodeintegerforkey:@"pointcount"]; // edit here @ughoavgfhw's comment mkmappoint* points = (mkmappoint*)[pointdata bytes]; // line ok? self = (rsroutepolyline*)[mkpolyline polylinewithpoints:points count:pointcount]; homecoming self; }
you should phone call init method on subclass of nsobject. since mkpolyline nsobject, should init it.
but mkpolyline has no methods , no init. objective c's of telling you can't subclass it.
instead, wduk suggested, define own class. keeps track of list point points, , manages nscoding save , restore them needed.
@interface rspolyline: nsobject<nscoding> - (id) initwithpoints: (nsarray*) points; - (id) initwithcoder:(nscoder *)adecoder; - (void) encodewithcoder:(nscoder *)acoder; - (mkpolyline*) polyline; @end
your class can generate polyline on request, perhaps caching result if performance issue.
as rule, don't reach inheritance first. when want extend , improve class, think first of composition.
ios objective-c cocoa-touch nscoding
No comments:
Post a Comment