zoukankan      html  css  js  c++  java
  • ObjectiveC difference between class method and static method?

     Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance.

    This describes exactly what Objective-C's class methods are not.

    An Objective-C class method very much requires an instance that is the target of the method invocation. That is, it requires an instance of the metaclass that describes the class object being invoked.

    Unlike static methods, Objective-C's class methods can be inherited (which, in combination with having the aforementioned self, is exactly why many classes can share a single, simple, implementation of+alloc on NSObject without needing their own custom implementations) and invoking a class method goes through the exact same objc_msgSend* based dispatch mechanism as any other method call site.

    Objective-C's class methods can be overridden across the class hierarchy and they can be swizzled.

    None of which is supported in languages that typically offer static methods in lieu of class methods.

    The bottom line is that static methods and class methods are very different. While that difference is mostly transparent for day to day coding purposes, there are still situations where knowing how class methods work can save you a ton of unnecessary lines of code.

    For example, you can't do this with static methods:

    @interface AbstractClass:NSObject
    + factory;
    @end
    
    @implementation AbstractClass
    + factory
    {
        return [[[self alloc] init] autorelease];
    }
    @end
    
    @interface Concrete1:AbstractClass
    @end
    @implementation Concrete1
    @end
    @interface Concrete2:AbstractClass
    @end
    @implementation Concrete2
    @end
    
    void foo() {
        Concrete1 *c = [Concrete1 factory];
        Concrete2 *d = [Concrete2 factory];
        ... etc ...
    }    
    

    http://stackoverflow.com/questions/8089186/objective-c-difference-between-class-method-and-static-method

     

     

  • 相关阅读:
    [已解决]报错:Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m;
    比较asyncio.run_coroutine_threadsafe 和 run_in_executor的区别
    sql server表结构对比
    sql server乱码显示问题
    sql server表分区系列【转】
    无法使用备份文件,因为原先格式化该文件时所用扇区大小为 512,而目前所在设备的扇区大小为 4096
    notepad++安装SQL格式化插件
    Linux学习笔记(21)linux查看系统状态
    mysql导入报错 [Err] 1273
    mysql cte
  • 原文地址:https://www.cnblogs.com/season2009/p/2567653.html
Copyright © 2011-2022 走看看