boscarol
boscarol

Reputation: 1941

Accessing same piece of code from two classes

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

Answers (3)

Antonio MG
Antonio MG

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:

Customizing Existing Classes

Upvotes: 4

Hot Licks
Hot Licks

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

viggio24
viggio24

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

Related Questions