Reputation: 3121
Basically I have 2 methods that are similar in functionality. The only difference is the class container that are different. What I am trying to achieve is to unify these 2 methods and somehow have the container be dynamic.
here are the 2 methods:
-(NSMutableArray*) parseRequest:(NSArray*)elements {
NSMutableArray *currentStruct = [NSMutableArray array];
for (id element elemets) {
// This is where the difference is
FriendRequest *friend = [[FriendRequest alloc] init];
if(nickname != nil) {
friend.nickname = [element objectAtIndex:0];
}
[currentStruct addObject:friend];
[friend release];
}
return currentStruct;
}
Second:
-(NSMutableArray*) parseRequest:(NSArray*)elements {
NSMutableArray *currentStruct = [NSMutableArray array];
for (id element elemets) {
// This is where the difference is
Friend *friend = [[Friend alloc] init];
if(nickname != nil) {
friend.nickname = [element objectAtIndex:0];
}
[currentStruct addObject:friend];
[friend release];
}
return currentStruct;
}
Upvotes: 1
Views: 97
Reputation: 3746
Or you can use the factory pattern:
-(NSMutableArray*) parseRequest:(NSArray*)elements factory:(SEL)factory {
NSMutableArray *currentStruct = [NSMutableArray array];
for (id element elemets) {
NSObject *friend = [self performSelector:factory];
if(nickname != nil) {
[friend performSelector:@selector(setNickname) withObject:[element objectAtIndex:0]];
}
[currentStruct addObject:friend];
}
return currentStruct;
}
-(Friend*) friendFactory {
return [[[Friend alloc] init] autorelease];
}
Upvotes: 1
Reputation: 523494
Make that class a parameter.
-(NSMutableArray*) parseRequest:(NSArray*)elements withClass:(Class)friendClass {
NSMutableArray *currentStruct = [NSMutableArray array];
for (id element elemets) {
// This is where the difference is
id friend = [[friendClass alloc] init]; // <---
if(nickname != nil) {
[friend setNickname:[element objectAtIndex:0]];
}
[currentStruct addObject:friend];
[friend release];
}
return currentStruct;
}
...
-(NSMutableArray*) parseRequest:(NSArray*)elements {
return [self parseRequest:elements withClass:[Friend class]];
}
Upvotes: 1