类组合如何在iOS中运行? [英] How does class composition work in iOS?
问题描述
假设我在 classA
上有属性 A
,属性 B
on classB
我希望 classAB
同时拥有两个属性 A
和 B
。我仍然不明白如何使用组合来完成所有工作。
Let's say I have property A
on classA
and property B
on classB
and I want classAB
to have both properties A
and B
. I still don't understand how to make this all work with composition.
我意识到这可以通过继承完成,但我想要了解如何使用组合执行此操作。我看了一些例子,但我仍然不知道它是如何工作的。
I realize this can be done with inheritance, but I want to learn how to do this with composition. I've looked at examples and I still don't get how it all works.
推荐答案
你创建了一个新课程,将classA和classB的实例作为成员变量。然后通过传递get / set方法实现属性。
You make a new class, which has instances of classA and classB as member variables. Then you implement the properties by passing through the get/set methods.
@interface ClassAB
{
ClassA *objectA;
ClassB *objectB;
}
@property (nonatomic,strong) id propertyA;
@property (nonatomic,strong) id propertyB;
@end
@implementation ClassAB
- (id)propertyA { return objectA.propertyA; }
- (void)setPropertyA:(id)value { objectA.propertyA = value; }
- (id)propertyB { return objectB.propertyB; }
- (void)setPropertyB:(id)value { objectB.propertyB = value; }
@end
这就是组成。有些语言有特殊的语法来执行此操作(例如,在Ruby中,您可以包含一组来自另一个类/模块的方法),但Objective-C不允许这样做。
And that's what composition is. Some languages have special syntax to do this (e.g., in Ruby you can include a set of methods from one class/module in another), but Objective-C doesn't allow this.
你可以在Objective-C中做的一件事就是捕获发送给你的对象的消息,这些消息没有相关的方法,并将它们转发给另一个对象。如果您正在编写一个将作为另一个类构成的类,或者如果要转发许多不同的消息并且您不想手动将它们全部写出来,这个技巧很有用。
One thing you can do in Objective-C is catch messages sent to your object which do not have an associated method, and forward them to another object. This trick is useful if you are writing a class that will pose as another class, or if there are many different messages to forward and you don't want to write them all out manually.
使用消息转发的缺点是您放弃了某些控制,并且在您的类或转发类处理消息时可能更难预测。例如,如果超类实现了一个方法,那么将执行该方法,并且不会调用转发代码。
The downside to using message forwarding is that you give up some control and it can be a harder to predict when a message will be handled by your class or the forwarding class. For example, if a superclass implements a method, that method will be executed and the forwarding code will not be called.
这篇关于类组合如何在iOS中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!