Objective-C protocol vs inheritance vs extending?

南楼画角 提交于 2020-01-17 03:27:09

问题


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).


回答1:


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.




回答2:


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.)



来源:https://stackoverflow.com/questions/2993431/objective-c-protocol-vs-inheritance-vs-extending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!