如何在不引用类的情况下在Objective C中调用+ class方法? [英] How do I call +class methods in Objective C without referencing the class?
问题描述
我有一系列策略"对象,我认为将这些对象方便地实现为一组策略类上的类方法.我为此指定了一个协议,并创建了要遵守的类(如下所示)
I have a series of "policy" objects which I thought would be convenient to implement as class methods on a set of policy classes. I have specified a protocol for this, and created classes to conform to (just one shown below)
@protocol Counter
+(NSInteger) countFor: (Model *)model;
@end
@interface CurrentListCounter : NSObject <Counter>
+(NSInteger) countFor: (Model *)model;
@end
然后我有一个符合该协议的类的数组(就像CurrentListCounter一样)
I then have an array of the classes that conform to this protocol (like CurrentListCounter does)
+(NSArray *) availableCounters {
return [[[NSArray alloc] initWithObjects: [CurrentListCounter class], [AllListsCounter class], nil] autorelease];
}
请注意我是如何使用类似对象的类的(这可能是我的问题-在Smalltalk类中,对象是与其他所有对象一样的-我不确定它们是否在Objective-C中吗?)
Notice how I am using the classes like objects (and this might be my problem - in Smalltalk classes are objects like everything else - I'm not sure if they are in Objective-C?)
我的确切问题是当我从数组中取出一个策略对象时要调用该方法:
My exact problem is when I want to call the method when I take one of the policy objects out of the array:
id<Counter> counter = [[MyModel availableCounters] objectAtIndex: self.index];
return [counter countFor: self];
我在return语句上收到警告-它说-countFor:在协议中找不到(因此假设它是我要调用类方法的实例方法).但是,由于数组中的对象是类的实例,所以它们现在就像实例方法(或者从概念上讲应该是实例方法).
I get a warning on the return statement - it says -countFor: not found in protocol (so its assuming its an instance method where I want to call a class method). However as the objects in my array are instances of class, they are now like instance methods (or conceptually they should be).
是否有一种神奇的方法来调用类方法?还是这只是个坏主意,我应该只创建策略对象的实例(而不使用类方法)?
Is there a magic way to call class methods? Or is this just a bad idea and I should just create instances of my policy objects (and not use class methods)?
推荐答案
此
id <Counter> counter = [[Model availableCounters] objectAtIndex:0];
return ( [counter countFor: nil] );
应该是
Class <Counter> counter = [[Model availableCounters] objectAtIndex:0];
return ( [counter countFor: nil] );
在第一个实例中,您有一个符合<Counter>
的实例.在第二个中,您有一个符合<Counter>
的类.编译器警告是正确的,因为符合<Counter>
的实例不会响应countFor:
,只有类会响应.
In the first you have an instance that conforms to <Counter>
. In the second you have a class that conforms to <Counter>
. The compiler warning is correct because instances that conform to <Counter>
don't respond to countFor:
, only classes do.
这篇关于如何在不引用类的情况下在Objective C中调用+ class方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!