Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing NSString

Tags:

nsstring

Using WSDL2ObjC I am getting lot of classes which are subclasses of NSString. I am finding it troublesome to initialize the NSString value of any object of those classes.

Say my class looks like this :

@interface mClass ; NSString {
     int value;
}

Now in my code I would like to use objects of mClass as both NSString and also want to use its attribute value which is an integer.

How can I do that?

I am trying to use code like this

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

But it's showing me an error saying I am using an abstract object of a class , I should use concrete instance instead.

like image 590
rahduro Avatar asked Oct 17 '25 16:10

rahduro


1 Answers

If you really need make NSString subclass you should override 3 methods:

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

For example:

MyString.h

@interface MyString : NSString 

@property (nonatomic, strong) id myProperty;

@end


MyString.m

@interface MyString ()

@property (nonatomic, strong) NSString *stringHolder;

@end

@implementation 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
like image 190
Vlad Papko Avatar answered Oct 21 '25 03:10

Vlad Papko