[英]Self in Class Method
I am reading some Objective-C code in a well-maintained GitHub repo. 我正在维护良好的GitHub存储库中阅读一些Objective-C代码。 https://github.com/soffes/sskeychain/blob/master/SSKeychain.m
https://github.com/soffes/sskeychain/blob/master/SSKeychain.m
I came across some weird lines (at least weird to my eyes). 我碰到了一些奇怪的字眼(至少在我看来是奇怪的)。
+ (NSArray *)allAccounts {
return [self accountsForService:nil error:nil];
}
I was taught that self refers to the instance itself in an instance method. 有人告诉我self在实例方法中引用实例本身。 So what does self mean here, in a class method?
那么在类方法中, 自我在这里是什么意思?
Inside class methods, self
refers to the object representing the corresponding Class
: 在类方法中,
self
表示代表相应Class
的对象:
+ (NSArray *)allAccounts {
NSLog("%@", [self description]); // Will print the name of the class
return [self accountsForService:nil error:nil];
}
This is the same object that you get in an instance method when you call [self class]
. 这是调用
[self class]
时在实例方法中获得的对象。
It is useful if you would like to call methods on the class
polymorphically. 如果您想多态调用
class
上的方法,这将很有用。 For example, you can call [[self alloc] init]
to create a new instance of the class on which the call is performed. 例如,您可以调用
[[self alloc] init]
创建在其上执行调用的类的新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.