Ell*_*iot 17 cocoa cocoa-touch objective-c
风格方面(和功能上,如果有任何区别),用于声明私有方法,哪些更好?
@interface MyClass()
@interface MyClass(private)
Run Code Online (Sandbox Code Playgroud)
bbu*_*bum 42
这两种语法有不同的用途.
命名类别 - @interface Foo(FooCategory) - 通常用于:
(1)通过添加功能扩展现有类.示例:Foundation中的NSAttributedString由AppKit中的类别扩展,该类别添加了AppKit特定的类似RTF的文本格式API.
(2)声明委托可能会或可能不会实现的一组方法.示例:各种类声明 - 但不实现 - @interface NSObject(SetODelegateMethods).
由于@protocol已经扩展到支持Objective-C 2.0中的@optional方法,因此表格(2)已经失宠了.
类扩展 - @interface Foo() - 旨在允许您声明用于实现类内部的其他私有API - SPI或系统编程接口.这通常出现在.m文件的顶部.在类扩展中声明的任何方法/属性必须在@implementation中实现,就像在public @interface中找到的方法/属性一样.
在@ synthesize访问器之前,类扩展也可用于重新声明公共只读@property作为读写.
例:
foo.h中
@interface Foo:NSObject
@property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)