Skip to content
This repository has been archived by the owner on Nov 4, 2019. It is now read-only.

Code style guide

pbdeuchler edited this page Jun 8, 2011 · 17 revisions

Code style guide

Kod follows the Google Objective-C Style Guide.

  • Kod types and constants are prefixed with "K"
  • Kod functions and variables are prefixed with "k"

It's recommended to install the Google Toolbox For Mac Xcode Plugin which adds features like a preference to clean up end of line white space from text files.

Example

They say an example is worth a thousand words so let's start off with an example that should give you a feel for the style, spacing, naming, etc.

An example header file, demonstrating the correct commenting and spacing for an @interface declaration

// A sample class demonstrating good Objective-C style. All interfaces,
// categories, and protocols (read: all top-level declarations in a header)
// should be commented. Comments must also be adjacent to the object they're
// documenting.
//
// (no blank line between this comment and the interface)
@interface KFoo : NSObject {
  NSString *foo_;
  NSString *bar_;
}

// Returns an autoreleased instance of KFoo. See -initWithString: for details
// about the argument.
+ (id)fooWithString:(NSString *)string;

// Designated initializer. |string| will be copied and assigned to |foo_|.
- (id)initWithString:(NSString *)string;

// Prefer @properties to traditional getters/setters.
@property(assign) NSString *foo;

// Label for the xyz
@property(assign) NSString *bar;

// Does some work on |blah| and returns YES if the work was completed
// successfuly, and NO otherwise.
- (BOOL)doWorkWithString:(NSString *)blah;

@end

An example source file, demonstating the correct commenting and spacing for the @implementation of an interface. It also includes the reference implementations for important methods like getters and setters, init, and dealloc.

#import "KFoo.h"

@implementation KFoo

// Prefer to use synthesized property implementations
@synthesize foo = foo_;

+ (id)fooWithString:(NSString *)string {
  return [[[self alloc] initWithString:string] autorelease];
}

// Must always override super's designated initializer.
- (id)init {
  return [self initWithString:nil];
}

- (id)initWithString:(NSString *)string {
  if ((self = [super init])) {
    foo_ = [string retain];
    bar_ = [[NSString alloc] initWithFormat:@"hi %d", 3];
  }
  return self;  
}

- (void)dealloc {
  [foo_ release];
  [bar_ release];
  [super dealloc];
}

- (NSString *)bar {
  return bar_;
}

- (void)setBar:(NSString *)bar {
  [bar_ autorelease];
  bar_ = [bar retain];  
}

- (BOOL)doWorkWithString:(NSString *)blah {
  // ...
  return NO;
}

@end
Clone this wiki locally