我正在尝试对NSMutableData进行子类化,以在不复制的情况下为子数据添加功能。这是代码
@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
但是问题是当我尝试实例化myMutableData时,出现了此错误
"-initWithCapacity: only defined for abstract class. Define -[myMutableData initWithCapacity:]!'"
为什么?那么继承不起作用?谢谢
最佳答案
这需要一个类别。但是,类别默认情况下不能具有属性和实例变量。因此,您需要#import <objc/runtime.h>
并使用关联的对象来获取和设置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