Adding Rows

There are a number of ways to add rows to a table view at runtime. The built-in behavior for adding a row is to display a new row with a green plus sign icon. However, this technique has fallen out of favor in iOS applications because it’s cumbersome to enter editing mode and then find the row with the plus sign icon – especially in larger tables.

So we’re going to put a New button in the header view instead. Recall that when a table view first appears on screen, it asks its data source for the data it needs to display, and the data source provides it. You can force this process to run again by sending the message reloadData to the table view. That way, if you add a Possession to the PossessionStore, you can reload the table, and the new Possession will be included in the data sent to the table for display.

In ItemsViewController.m, implement the action method for the New button so that a new random Possession is added to the store and the table is reloaded.

-​ ​(​I​B​A​c​t​i​o​n​)​a​d​d​N​e​w​P​o​s​s​e​s​s​i​o​n​:​(​i​d​)​s​e​n​d​e​r​
{​
 ​ ​ ​ ​[​[​P​o​s​s​e​s​s​i​o​n​S​t​o​r​e​ ​d​e​f​a​u​l​t​S​t​o​r​e​]​ ​c​r​e​a​t​e​P​o​s​s​e​s​s​i​o​n​]​;​

 ​ ​ ​ ​/​/​ ​t​a​b​l​e​V​i​e​w​ ​r​e​t​u​r​n​s​ ​t​h​e​ ​c​o​n​t​r​o​l​l​e​r​'​s​ ​v​i​e​w​
 ​ ​ ​ ​[​[​s​e​l​f​ ​t​a​b​l​e​V​i​e​w​]​ ​r​e​l​o​a​d​D​a​t​a​]​;​
}​

Notice the tableView message that the ItemsViewController sends itself. Every UITableViewController implements tableView, which returns the table controller’s view. Because we know this method returns an instance of UITableView, we can send it UITableView-specific messages, like reloadData.

Build and run the application and tap your New button. A new random possession will appear at the bottom of the table.

Now that you have the ability to add rows, remove the code in the init method in ItemsViewController.m that immediately puts 10 random possessions into the store. The init method should now look like this:

-​ ​(​i​d​)​i​n​i​t​
{​
 ​ ​ ​ ​/​/​ ​C​a​l​l​ ​t​h​e​ ​s​u​p​e​r​c​l​a​s​s​'​s​ ​d​e​s​i​g​n​a​t​e​d​ ​i​n​i​t​i​a​l​i​z​e​r​
 ​ ​ ​ ​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​W​i​t​h​S​t​y​l​e​:​U​I​T​a​b​l​e​V​i​e​w​S​t​y​l​e​G​r​o​u​p​e​d​]​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
}​

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.26.221