Objective-C class extension

前端 未结 5 734
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 18:07

As a fairly new objective-c programmer (with a 4 years Java experience), I seem to be having a hard time understanding when to use class extensions. From what I understood (

5条回答
  •  Happy的楠姐
    2020-12-13 18:57

    the main difference between categories and extensions is that the extension expects you to implement the methods inside your main implementation, whereas with a category, it can be in another implementation. It also seems that people are using extensions mainly for private methods.

    Correct.

    What's the difference between using a class extension to declare a private method, and not declare it at all (it seems to compile in run in both cases)?

    Maybe just a compiler warning regarding the undeclared selector. (Of course it runs fine - the method is implemented and does exist.) Also note that a declaration (a known, correct function signature) is necessary for the compiler in order to emit ABI-conformant, correct binary code. The assumption it makes about undeclared methods (namely that they return id and accept variadic arguments) may not be correct - calling a function through a pointer of an incompatible type is undefined behavior.

    What's the difference between declaring ivars inside the extension and declaring it directly inside the implementation?

    In the 4th example, it's a global C variable, it's not an instance variable of your class.

    when should I put an underscore (_) in front of a variable's name?

    Whenever you want, just do it consistently. Always or never.

提交回复
热议问题