nsstring - 子类化 NSString

标签 nsstring

使用 WSDL2ObjC 我得到了很多类,它们是 NSString 的子类。 我发现初始化这些类的任何对象的 NSString 值很麻烦。

假设我的类(class)是这样的:

@interface mClass ; NSString {
     int value;
}

现在在我的代码中我想使用 mClass 的对象作为 NSString 并且还想使用它的属性值,它是一个整数。

我该怎么做?

我正在尝试使用这样的代码

 mClass *obj = [[mClass alloc] initWithString:@"Hello"];

但它向我显示一个错误,说我正在使用类的抽象对象,我应该改用具体实例。

最佳答案

如果你真的需要创建 NSString 的子类,你应该覆盖 3 个方法:

- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;
- (NSUInteger)length;
- (unichar)characterAtIndex:(NSUInteger)index;

例如:

MyString.h

@interface MyString : NSString 

@property (nonatomic, strong) id myProperty;

@end


MyString.m

@interface MyString ()

@property (nonatomic, strong) NSString *stringHolder;

@end

@implemenation MyString

- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer {
    self = [super init];
    if (self) {
        self.stringHolder = [[NSString alloc] initWithCharactersNoCopy:characters length:length freeWhenDone:freeBuffer];
    }
    return self;
}

- (NSUInteger)length {
    return self.stringHolder.length;
}

- (unichar)characterAtIndex:(NSUInteger)index {
    return [self.stringHolder characterAtIndex:index];
}

@end

关于nsstring - 子类化 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6895012/

相关文章:

objective-c - 奇怪的 NSString 泄漏

ios - 将 NSURL 转换为 NSString

IOS:将字符串转换为十六进制数组

xml - NSString stringWithContentsOfURL 已弃用。我应该怎么办?

cocoa - NSArray objectAtIndex 不起作用。请帮忙

iphone - NSString stringWithFormat 调用 XX 次导致内存警告

iphone - NSArray 的前三项变成 NSString?

ios - 如何在 swift 中使用 NSUserDefaults 保存字符串数组

ios - 将 objective-c 数组转换为小写并且没有额外的格式

iphone - 如何使用 AirPrint 打印 NSString?