例子
他们说一个例子胜过千言万语,让我们开始用一个例子让你感受Objective-C的风格,间距,命名等。
一个头文件的例子,展示了@interface声明的正确注释和间距:
#import <Foundation/Foundation.h>
// A sample class demonstrating good Objective-C style. All interfaces,
// categories, and protocols (read: all top-level declarations in a header)
// MUST be commented. Comments must also be adjacent to the object they're
// documenting.
//
// (no blank line between this comment and the interface)
@interface Foo : NSObject {
@private
NSString *_bar;
NSString *_bam;
}
// Returns an autoreleased instance of Foo. See -initWithBar: for details
// about |bar|.
+ (id)fooWithBar:(NSString *)bar;
// Designated initializer. |bar| is a thing that represents a thing that
// does a thing.
- (id)initWithBar:(NSString *)bar;
// Gets and sets |_bar|.
- (NSString *)bar;
- (void)setBar:(NSString *)bar;
// Does some work with |blah| and returns YES if the work was completed
// successfully, and NO otherwise.
- (BOOL)doWorkWithBlah:(NSString *)blah;
@end
一个源文件的例子,展示了一个接口的@implementation的正确注释和间距。它也包含一些重要方法,像getters、setters、init和dealloc的参考实现:
#import "Foo.h"
@implementation Foo
+ (id)fooWithBar:(NSString *)bar {
return [[[self alloc] initWithBar:bar] autorelease];
}
// Must always override super's designated initializer.
- (id)init {
return [self initWithBar:nil];
}
- (id)initWithBar:(NSString *)bar {
if ((self = [super init])) {
_bar = [bar copy];
_bam = [[NSString alloc] initWithFormat:@"hi %d", 3];
}
return self;
}
- (void)dealloc {
[_bar release];
[_bam release];
[super dealloc];
}
- (NSString *)bar {
return _bar;
}
- (void)setBar:(NSString *)bar {
[_bar autorelease];
_bar = [bar copy];
}
- (BOOL)doWorkWithBlah:(NSString *)blah {
// ...
return NO;
}
@end
在@interface、@implementation和@end前后的空行是可选的。如果你的@interface声明了实参,那么右括号之后需要有一个空行。
除非interface或implementation很短,比如,当定义一小部分私有方法或一个桥接类时,添加空行通常有利于可读性。