[英]Objective C syntax question
我看到UIColor类可以像这样[UIColor redColor]调用变量; 如何编写我的课程来做同样的事情? 另外,例如,我可以只为类提供一种方法吗?
[MyClass CallingMyMethod];
谢谢。
是。 在声明方法时,只需使用+
而不是-
:
+ (void)callingMyMethod
{
...
}
您必须创建一个类方法。 类方法的定义类似于实例方法,但是具有+
而不是-
:
@interface MyClass : NSObject
+ (id)classMethod;
- (id)instanceMethod;
@end
@implementation MyClass
+ (id)classMethod
{
return self; // The class object
}
- (id)instanceMethod
{
return self; // An instance of the class
}
请注意,在类方法中, self
变量将引用该类,而不是该类的实例。
是的,它们是呼叫类别消息。 定义消息时,使用+
而不是-
。
像这样:
@interface MyClass : NSObject
{
}
+ (void) callingMyMethod;
使用+
而不是-
。 这称为类方法,用于初始化和返回对象。
@interface SomeClass : NSObject + (id)callingMyMethod; - (id)otherMethod; @end @implementation SomeClass + (id)callingMyMethod { return self; // The class object } - (id)otherMethod { return self; // An instance of the class }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.