开发者

Questions regarding Objective-C private method example

开发者 https://www.devze.com 2023-01-14 14:05 出处:网络
The following is an example of how to create \'private\' methods in Objective-C: MyC开发者_如何学Class.m

The following is an example of how to create 'private' methods in Objective-C:

MyC开发者_如何学Class.m

#import "MyClass.h"
#import <stdio.h>

@implementation MyClass
-(void) publicMethod {
    printf( "public method\n" );
}
@end

// private methods
@interface MyClass (Private)
-(void) privateMethod;
@end

@implementation MyClass (Private)
-(void) privateMethod {
    printf( "private method\n" );
}
@end

Why does this example use the (Private) category name in the @interface MyClass (Private) and @implementation MyClass (Private) declarations? Aren't interfaces declared in .m files automatically private? Do we need 2 different implementation blocks?

Is there a variation of this technique to create 'protected' methods?

(I'm new to objective-C. Am I missing the point of category names? Why do we need to use them in this instance?)

Thanks-


If you're creating a category, you have to give it some name. The name Private for the category doesn't have any special meaning to the language.

Also, in modern Objective-C, this would be a better case for a class extension, which is declared like a nameless category (@interface MyClass ()) but the implementation goes in the main @implementation block. This is a relatively recent addition, though. The secret-category method in your example is the more traditional way of accomplishing roughly the same thing.


The (Private) part declares a category for MyClass. The category name can be anything, but all categories interpreted by the compiler will add the methods from that category to the list of known methods for that class as a whole. By putting the private methods in a category at the top of a source file, you can declare the public interface to your class in your main .h file but all of your private methods will be “hidden” inside the .m file, all the while you are still able to use those methods without the compiler warning that the methods weren't found.

The category name is only to “categorise” the methods of a class. You can categorise them any way you want. The name is not important, simply calling the category Private does not make those methods private, they are still able to be overridden by subclasses and able to be discovered by introspection.

Basically, you are just separating the public interface from your class from your private interface. If you have to ship a library with its headers, the headers will not contain any of the private methods.

Typically though, the private interface is placed at the top of the source file so that the compiler interprets it (and finds all the methods that the category provides) before interpreting your main and private implementations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号