You may have noticed that when you start typing the word init, Xcode will automatically add an init implementation in your source file. If you haven’t noticed this, go ahead and type init in an implementation file and wait for the code-completion to kick in.
The freebie code comes from the code snippet library. You can see the code snippet library by opening the utilities area and selecting the icon in the library selector (Figure 10.13). Alternatively, you can use the shortcut Command-Control-Option-2, which reveals the utilities area and the Code Snippet Library. Substituting another number in the shortcut selects the corresponding library.
Notice that there are a number of code snippets available (Figure 10.13). Click on one, and in a moment, a window will appear with the details for that snippet. Click the Edit button on the code snippet detail window (Figure 10.14).
The Completion Shortcut field in the edit window shows you what to type in a source file to have Xcode add the snippet. This window also tells you that this snippet can be used in an Objective-C file as long as you are in the scope of a class implementation.
You can’t edit any of the pre-defined code snippets, but you can create your own. In ItemsViewController.m, locate the implementation of tableView:numberOfRowsInSection:. Highlight the entire method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[[PossessionStore defaultStore] allPossessions] count]; }
Drag this highlighted code into the code snippet library. The edit window will appear again, allowing you to fill out the details for this snippet.
One issue with this snippet is that the return statement is really specific to this application – it would be much more useful if the value returned was a code completion placeholder that you could fill in easily. In the edit window, modify the code snippet so it looks like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return <#number of rows#>; }
Then, fill out the rest of the fields in the edit window as shown in Figure 10.15 and click Done.
Back in ItemsViewController.m, start typing tablerows. Xcode will recommend this code snippet and pressing the return key will automatically complete it for you – and the number of rows placeholder will be selected. You’ll have to type in that bit of code to get the number of rows yourself. Snippets aren’t magical – just handy.
Make sure to remove the code entered by the snippet, since you have already defined tableView:numberOfRowsInSection: in ItemsViewController.m.
3.144.232.189