ios - How to subclass NSMutableData -
i trying subclass nsmutabledata add ability subdata without copying. here code
@interface mymutabledata : nsmutabledata - (nsdata *)subdatawithnocopyingatrange:(nsrange)range; @end @interface mymutabledata() @property (nonatomic, strong) nsdata *parent; @end @implementation mymutabledata - (nsdata *)subdatawithnocopyingatrange:(nsrange)range { unsigned char *dataptr = (unsigned char *)[self bytes] + range.location; mymutabledata *data = [[mymutabledata alloc] initwithbytesnocopy:dataptr length:range.length freewhendone:no]; data.parent = self; return data; } @end
but problem when try instantiate mymutabledata, got error
"-initwithcapacity: defined abstract class. define -[mymutabledata initwithcapacity:]!'"
why? inheritance not work?
this calls category. however, category cannot default have properties , instance variables. hence need #import <objc/runtime.h>
, use associated objects , set value of parent
.
@interface nsmutabledata(mymutabledata) - (nsdata *)subdatawithnocopyingatrange:(nsrange)range; @property (nonatomic, strong) nsdata *parent; @end @implementation nsmutabledata(mymutabledata) - (nsdata *)subdatawithnocopyingatrange:(nsrange)range { unsigned char *dataptr = (unsigned char *)[self bytes] + range.location; nsmutabledata *data = [[nsmutabledata alloc] initwithbytesnocopy:dataptr length:range.length freewhendone:no]; data.parent = self; return data; } -(nsdata*)parent { return objc_getassociatedobject(self, @selector(parent)); } -(void)setparent:(nsdata *)parent { objc_setassociatedobject(self, @selector(parent), parent, objc_association_retain_nonatomic); } @end
Comments
Post a Comment