Objective-C协议vs继承vs扩展? [英] Objective-C protocol vs inheritance vs extending?

查看:77
本文介绍了Objective-C协议vs继承vs扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类,它们的代码几乎相同.它们之间只有一两个字符串不同.我想做的是使它们从另一个定义了这些函数的类中变为"x",然后使用常量或其他方式来定义那些不同的字符串.我不确定"x"是继承还是扩展还是什么.这就是我需要的帮助.

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.

例如:

objectA.m:

objectA.m:

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

objectBob.m:

objectBob.m:

#define name @"Bob"

objectJoe.m

objectJoe.m

#define name @"Joe"

(我不确定定义字符串是否合法,但这很重要)

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

如果objectBob.m和objectJoe.m甚至不必定义方法,而只需定义它们与objectA.m的关系,那将是理想的选择.有什么办法可以做这样的事情吗?这有点像协议,但是相反,我希望协议"实际定义功能.

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.

如果所有其他方法都失败了,我将创建objectA.m:

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

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

并让其他文件调用该函数(仅#import objectA.m).

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

推荐答案

只需在子类中创建一个-name方法(您需要一个基类,然后为每种类型创建一个子类).

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

然后做:

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

修复了非objc之类的方法命名. 再次固定方法.

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

这篇关于Objective-C协议vs继承vs扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆