Best way to define private methods for a class in Objective-C

后端 未结 12 1941
小鲜肉
小鲜肉 2020-11-22 14:34

I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.

I understand there

12条回答
  •  长情又很酷
    2020-11-22 15:22

    There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClass as the public methods. So I structure my classes like this:

    In the .h file:

    @interface MyClass {
        // My Instance Variables
    }
    
    - (void)myPublicMethod;
    
    @end
    

    And in the .m file:

    @interface MyClass()
    
    - (void)myPrivateMethod;
    
    @end
    
    @implementation MyClass
    
    - (void)myPublicMethod {
        // Implementation goes here
    }
    
    - (void)myPrivateMethod {
        // Implementation goes here
    }
    
    @end
    

    I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.

提交回复
热议问题