Reputation: 1941
I have two classes each with an instance method that use the same piece of code.
This piece of code takes a NSString and return an NSArray.
Currently the same piece of code is repeated in the two classes.
Is there a way to write it separately and call it by the two classes? I tried to make a method in a subclass of NSArray, but there are many problems due to the fact that NSArray is an abstract class. Any suggestions?
Thank you.
Upvotes: 0
Views: 79
Reputation: 20410
Instead of subclassing NSArray, the correct approach to extent the behaviour of a class is to create a category on that class.
So, you can create a category on NSString that returns an array, and after you have imported that category to your project, you can call it as if it was part of NSString, for example:
NSString *myString = @"Hello";
NSArray *myArray = [myString generateArrayFromString];
You can find a guide on how to create a category here:
Upvotes: 4
Reputation: 47729
From the sound of it (parsing a string into an NSArray, with on reference to the class's instance fields) you can make the method a class (vs instance) method and invoke it from either class.
Ie:
+(NSArray*)parseThisString:(NSString*)theString {
doSomething;
return result;
}
Invoke with [TheNameOfTheClass parseThisString:inputString]
.
Of course, if you are reverencing values in the class's instance this won't work.
Upvotes: 0
Reputation: 12366
You can try to make a NSString category. This category will return the array. E.g.:
//
// NSString+MyCategory.h
#import
@interface NSString (MyCategory)
-(NSArray *)myMethod;
@end
//
// NSString+MyCategory.m
#import "NSString+MyCategory.h"
@implementation NSString (MyCategory)
-(NSArray *)myMethod {
NSArray *_arr = [self componentsSeparatedByString:@","];
return _arr;
}
@end
Then in your class (or whatever you want in your code) you can import the category:
#import "NSString+MyCategory.h"
and then use it on any string:
NSArray *myArray = [anyString myMethod];
Upvotes: 1