我有一个从UIView定义的类集合。
@interface {
UIView *thisView
UIView *thatView
}
。
thisView *viewOne = [[thisView alloc] init];
thatView *viewTwo = [[thatView alloc] init];
现在,假设我想创建一个方法,该方法将接受这些对象并调用它们共同的函数,并设置公共参数并执行各种未知的事情,如果它们属于不同的类,我如何将这些对象传递给它(假设它们非常不同)?
[self exampleMethod:viewOne];
[self exampleMethod:viewTwo];
- (void)exampleMethod:(UIView *)viewNumber //will this suffice?
{
[viewNumber anotherMethod];
。
两种最常见的做法是:
-
创建一个包含所有"共同点"(方法、属性等)的
UIView
子类(exampleClass
),然后将thisView
和thatView
类定义为exampleClass
的子类。然后,您可以将exampleClass
用作exampleMethod
中的参数。 -
创建一个协议,然后让
thisView
和thatView
实现该协议。
这两种技术都是Objective-C(和面向对象编程)的基础,在投入大量时间编写代码之前,可能值得更多地了解它们。
如果有一个公共父类响应您计划发送的消息,则可以按该变量键入该变量。否则,您可以创建指定通用接口的协议。
如果要使用通用对象,可以检查它们是否响应要执行的消息。然后执行该消息。
id blah;
if ([blah respondsToSelector:@selector(someMethod:)])
{
[blah performSelector:@selector(someMethod:) withObject:anObject];
}
为您的示例
- (void)exampleMethod:(UIView *)viewNumber //will this suffice?
{
if ([viewNumber respondsToSelector:@selector(anotherMethod)])
{
[viewNumber performSelector:@selector(anotherMethod)];
}
}