Style-wise (and functionally, if there is any difference), for declaring private methods, which of these is better?
@interface MyClass()
@interface MyClass(private)
Style-wise (and functionally, if there is any difference), for declaring private methods, which of these is better?
@interface MyClass()
@interface MyClass(private)
Yes,
there are the following differences.
1) Using anonymous categories requires implementing its methods in the main @implementation block for the corresponding class; anonymous categories allow you to declare additional required API for a class in locations other than within the primary class @interface block
2) When using MyClass(private), the following must be taken into account: object/category named pairs must be unique. If you declare a private category on your own class, then there are no problems. However, things are different on existing classes. For instance, only one NSString (Private) category can exist in a given Objective-C namespace. This can lead to problems because the Objective-C namespace is shared between the program code and all the libraries,frameworks,and plug-ins.This is especially important for Objective-C programmers writing screensavers,preference panes, and other plug-ins because their code will be injected into application or framework code that they do not control.
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