Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

objective c - Anonymous Category or "private" Category are they same?

Style-wise (and functionally, if there is any difference), for declaring private methods, which of these is better?

@interface MyClass()

@interface MyClass(private)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The two syntaxes serve different purposes.

A named category -- @interface Foo(FooCategory) -- is generally used to:

(1) extend an existing class by adding functionality. Example: NSAttributedString in Foundation is extended by a category in AppKit that adds AppKit specific RTF-like text formatting API.

(2) declare a set of methods that might or might not be implemented by a delegate. Example: Various classes declare -- but don't implement -- @interface NSObject(SetODelegateMethods).

Form (2) has fallen out of favor now that @protocol has been extended to support @optional methods in Objective-C 2.0.

A class extension -- @interface Foo() -- is designed to allow you to declare additional private API -- SPI or System Programming Interface -- that is used to implement the class innards. This typically appears at the top of the .m file. Any methods / properties declared in the class extension must be implemented in the @implementation, just like the methods/properties found in the public @interface.

Class extensions can also be used to redeclare a publicly readonly @property as readwrite prior to @synthesize'ing the accessors.

Example:

Foo.h

@interface Foo:NSObject
@property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end

Foo.m

@interface Foo()
@property(readwrite, copy) NSString *bar;
- (void) superSecretInternalSaucing;
@end

@implementation Foo
@synthesize bar;
.... must implement the two methods or compiler will warn ....
@end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...