代码之家  ›  专栏  ›  技术社区  ›  user362178

通过self调用类方法

  •  4
  • user362178  · 技术社区  · 16 年前

    Defining a Class

    id newInstance = [[self alloc] init];
    

    是一个很好的方法,使对象的同一类,自我是。据我所知,该语句使用self指针而不是类名调用类方法,因此我在我的应用程序中尝试了这种方法,尽管它可能会工作,但它会给出编译器警告。我真的不想被警告。

    2 回复  |  直到 6 年前
        1
  •  6
  •   Laurent Etiemble    16 年前

    self 表示类。

    例如,在 + (void)initialize 方法,通常可以看到:

    + (void)initialize {
        if (self == [MyClass class]) { // <- self is the current class
            // ...
        }
    }
    

    如果您真的想缩短类名而不重命名它,最简单的解决方案是使用 #define 声明:

    #define TCC TimingConfigController
    
    // The two lines are equivalent
    id result1 = [TimingConfigController theClassMethod]; 
    id result1 = [TCC theClassMethod];
    
        2
  •  3
  •   Philippe Leybaert    16 年前

    打电话 [[self alloc] init]

    id newInstance = [[[self class] alloc] init];