【问题标题】:Class method ios what does "self" refer to类方法ios“self”指的是什么
【发布时间】:2013-01-12 01:25:05
【问题描述】:
#import "ApiService.h"

@implementation ApiService
static ApiService *sharedInstance = nil;

+ (ApiService *)sharedInstance
{
    if (sharedInstance == nil)
    {
        sharedInstance =  [[self alloc]init];
    }

    return sharedInstance;
}

- (id)init
{
    if (self = [super init])
    {
    }
    return self;
}
@end

当我打电话给+sharedInstance 时,self 指的是什么?如何允许从 Class 方法调用 init?

【问题讨论】:

标签: objective-c singleton


【解决方案1】:

self 是类。

+ (id)create {
  return [[self alloc] init];
}

等同于:

+ (id)create {
  return [[SomeClass alloc] init];
}

或者在你的例子中:

+ (ApiService *)sharedInstance
{
    if (sharedInstance == nil)
    {
        sharedInstance =  [[ApiService alloc]init];
    }

    return sharedInstance;
}

这允许您从类方法调用self 上的类方法。它允许您在继承时在子类上调用它们,因为类方法也被继承。

【讨论】:

  • 如果self是类,那么当你做这样的事情时:self.property,那怎么可能是类?除非属性是静态的?
  • @Rob,objective-c中确实有2个self,检查developer.apple.com/library/ios/#documentation/General/…
  • 或者更好的表述:类本身就是对象,因此它们可以通过self向自己发送消息。 stackoverflow.com/questions/5773054/…
  • 看了链接,很奇怪,在 C++ 或 Java 中,你肯定不会使用这个术语,例如这不是班级...
  • 在类方法中使用 self 是有实际原因的。在继承场景中,使用“self”而不是“ApiService”将保证ApiService的子类不必重写“sharedInstance”方法并能够正确获取子类对象。这个技巧实际上在 Apple 的编程指南developer.apple.com/library/mac/documentation/cocoa/conceptual/… 中有所提及。在最底部,提示:不要在类工厂方法中使用 [[XYZPerson alloc] init],而是尝试使用 [[self alloc] init]。
猜你喜欢
  • 2019-12-06
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 2013-07-01
  • 2020-05-14
相关资源
最近更新 更多