views:

120

answers:

2

I have a couple classes that have nearly identical code. Only a string or two is different between them. What I would like to do is to make them "x" from another class that defines those functions and then uses constants or something else to define those strings that are different. I'm not sure if "x" is inheritance or extending or what. That is what I need help with.

For example:

objectA.m:

-(void)helloWorld {
    NSLog("Hello %@",child.name);
}

objectBob.m:

#define name @"Bob"

objectJoe.m

#define name @"Joe"

(I'm not sure if it's legal to define strings, but this gets the point across)

It would be ideal if objectBob.m and objectJoe.m didn't have to even define the methods, just their relationship to objectA.m. Is there any way to do something like this? It is kind of like protocol, except in reverse, I want the "protocol" to actually define the functions.


If all else fails I'll just make objectA.m:

-(void)helloWorld:(NSString *name) {
    NSLog("Hello %@",name);
}

And have the other files call that function (and just #import objectA.m).

+2  A: 

Just create a -name method in your subclasses (you want one base class, then a subclass for each type).

Then do:

- (void)helloWorld {
    NSLog(@"hello %@", [self name]);
}

Edit: fixed non-objc like method naming. Edit again: fixed method.

chpwn
+1 except that it'd be called "name" by cocoa naming standards.
Dave DeLong
Objective-C getter methods do not use the word `get`. It would just be `[self name]`. Methods beginning with `get` indicate that some supplied buffer is being filled or a remote resource is being fetched.
Chuck
That looks like that will work well. Could/should I couple that with a protocol that defines the functions that are needed by the base class (such as name)? Actually, does "name" need to be a method or is there a way to make it a constant for the subclass?
RyanJM
There's no reason for it not to be a method, Apple uses that same kind of idea itself a bunch...you could use an informal protocol, like I have there, or you could have a version in the base class that returns nil, requiring it to be overridden for the class to work.
chpwn
Thank you for your response. Can you also answer a related question for me? I put it here: http://stackoverflow.com/questions/2998903/objective-c-subclass-and-base-class-casting.
RyanJM
A: 

Sounds like inheritance to me. Define the helloWorld method as NSLog(@"Hello %@", name) and have the subclasses give different values to their name instance variables. (Note that I'm talking about instance variables, not preprocessor macros, which are useless for this purpose.)

Chuck
Is there any way to get away from instance variables and make it available for class methods? Or is the only way to do this be a method call like chpwn does?
RyanJM
Methods and instance variables are the only way to customize behavior by class. Why are you averse to using a method call?
Chuck