Roll src/third_party/WebKit 75a2fa9:2546356 (svn 202272:202273)
[chromium-blink-merge.git] / docs / cocoa_tips_and_tricks.md
blob2ab0329af5786f75046feb320e0f9ac2790f3ae5
1 # Cocoa Tips and Tricks
3 A collection of idioms that we use when writing the Cocoa views and controllers
4 for Chromium.
6 [TOC]
8 ## NSWindowController Initialization
10 To make sure that |window| and |delegate| are wired up correctly in your xib,
11 it's useful to add this to your window controller:
13 ```objective-c
14 - (void)awakeFromNib {
15   DCHECK([self window]);
16   DCHECK_EQ(self, [[self window] delegate]);
18 ```
20 ## NSWindowController Cleanup
22 "You want the window controller to release itself it |-windowDidClose:|, because
23 else it could die while its views are still around. if it (auto)releases itself
24 in the callback, the window and its views are already gone and they won't send
25 messages to the released controller."
26 - Nico Weber (thakis@)
28 See
29 [Window Closing Behavior, ADC Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Documents/Concepts/WindowClosingBehav.html#//apple_ref/doc/uid/20000027)
30 for the full story.
32 What this means in practice is:
34 ```objective-c
35 @interface MyWindowController : NSWindowController<NSWindowDelegate> {
36   IBOutlet NSButton* closeButton_;
38 - (IBAction)closeButton:(id)sender;
39 @end
41 @implementation MyWindowController
42 - (id)init {
43   if ((self = [super initWithWindowNibName:@"MyWindow" ofType:@"nib"])) {
44   }
45   return self;
48 - (void)awakeFromNib {
49   // Check that we set the window and its delegate in the XIB.
50   DCHECK([self window]);
51   DCHECK_EQ(self, [[self window] delegate]);
54 // NSWindowDelegate notification.
55 - (void)windowWillClose:(NSNotification*)notif {
56   [self autorelease];
59 // Action for a button that lets the user close the window.
60 - (IBAction)closeButton:(id)sender {
61   // We clean ourselves up after the window has closed.
62   [self close];
64 @end
65 ```
67 ## Unit Tests
69 There are four Chromium-specific GTest macros for writing ObjC++ test cases.
70 These macros are `EXPECT_NSEQ`, `EXPECT_NSNE`, and `ASSERT` variants by the same
71 names.  These test `-[id<NSObject> isEqual:]` and will print the object's
72 `-description` in GTest-style if the assertion fails. These macros are defined
73 in `//testing/gtest_mac.h`. Just include that file and you can start using them.
75 This allows you to write this:
77 ```objective-c
78 EXPECT_NSEQ(@"foo", aString);
79 ```
81 Instead of this:
83 ```objective-c
84 EXPECT_TRUE([aString isEqualToString:@"foo"]);
85 ```