Proper Objective-C Helper “Wannabe” Private methods?

前端 未结 3 471
南旧
南旧 2021-02-06 18:01

While I hate to beat a horse to death on this subject (I\'ve read through various articles about this), but would just like to get more opinions on this matter before I create m

3条回答
  •  遥遥无期
    2021-02-06 18:26

    Yes, it's perfectly reasonable to want to extract your functionality out into another method. The best way to do this in my opinion is using a class continuation, which you can put your private method declarations in. It can go above your @implementation block in your .m file, so it's not in the public header.

    @interface MyClass ()
    - (void)_privateMethod:(id)arg;
    @end
    

    The difference between a class continuation and a normal category (such as @interface MyClass (PrivateMethods)) is that the compiler will require you to implement the methods in your main @implementation block, rather than having a separate @implementation MyClass (PrivateMethods) block. This is arguably desirable when implementing helper methods like you described.

    In terms of naming, it's relatively common to start private method names (and ivar names, for that matter) with an _, though not everyone does — apparently Apple reserves this for themselves, so you should pick a different prefix. The language doesn't enforce anything.

提交回复
热议问题