简体   繁体   English

如何子类化NSMutableData

[英]How to subclass NSMutableData

I am trying to subclass NSMutableData to add the ability to subdata without copying. 我正在尝试对NSMutableData进行子类化,以在不复制的情况下为子数据添加功能。 Here is 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 the problem is when I try to instantiate myMutableData, I got this error 但是问题是当我尝试实例化myMutableData时,出现了此错误

"-initWithCapacity: only defined for abstract class.  Define -[myMutableData initWithCapacity:]!'"

Why? 为什么? So inheritance does not work? 那么继承不起作用? Thanks 谢谢

NSData and NSMutableData are part of a class cluster. NSDataNSMutableData是类群集的一部分。 That means you need to do more work when subclassing to ensure that your subclass is fully valid. 这意味着在子类化时需要做更多的工作,以确保子类完全有效。

In other words, don't subclass... 换句话说,不要继承……

It's much easier for you to do what you want using a category, a wrapper or a helper / utility class. 使用类别,包装器或帮助程序/实用程序类,您可以更轻松地完成所需的操作。 The best option is probably a wrapper which can return either the internal data directly or a specified range of the data. 最好的选择可能是包装器,它可以直接返回内部数据或指定范围的数据。

This calls for a category. 这需要一个类别。 However, a category cannot by default have properties and instance variables. 但是,类别默认情况下不能具有属性和实例变量。 Hence you need to #import <objc/runtime.h> and use associated objects to get and set value of parent . 因此,您需要#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM