How To Make A Shopping List App Python
In the previous lessen, we laid the foundation for the shopping list application. In the first part of this lesson, we'll further refine the application by enabling the user to edit and delete items from the list. In the second part of this lesson, we add the ability to select items from the list to create the shopping list.
Outline
As I mentioned in the previous article, one of the core features of the shopping list application is managing a list of items. We have done a great job so far, but the user should have the ability to edit and delete items from the list, which will be the focus of the first part of this tutorial. In the second part, we will implement the second core feature of the shopping list application, creating a shopping list by selecting items from the list of items.
9. Deleting Items
Deleting items from the list is an important addition in terms of user experience and overall usability. Adding this ability involves:
- removing the item from the view controller's
items
property - updating the table view
- saving the changes to disk
Let's see how this works in practice.
We first need to add an edit button to the navigation bar. In the view controller's viewDidLoad
method, create an instance of UIBarButtonItem
and assign it to the rightBarButtonItem
property of the view controller's navigationItem
property.
As in the previous lesson, we create a bar button item by calling the initWithBarButtonSystemItem:target:action:
initialization method. The first parameter that we pass is UIBarButtonSystemItemEdit
. In addition, we pass self
as the target and set the action to editItems:
.
- (void)viewDidLoad { [super viewDidLoad]; // NSLog(@"Items > %@", self.items); // Register Class for Cell Reuse [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier]; // Create Add Button self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem:)]; // Create Edit Button self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editItems:)]; }
The implementation of the editItems:
action is only one line of code as you can see below. Whenever the user taps the edit button, the table view is toggled into or out of edit mode. We do this by using a little trick. We ask the table view whether it currently is in edit mode, which returns a BOOL
value, and inverse the returned value (YES
becomes NO
and vice versa). The method we call on the table view is setEditing:animated:
, which is a specialized setter that accepts an animation parameter.
- (void)editItems:(id)sender { [self.tableView setEditing:![self.tableView isEditing] animated:YES]; }
If you run the shopping list application in the iOS Simulator and tap the edit button, you should see the table view being toggled into and out of edit mode.
Two methods of the UITableViewDataSource
protocol are important for enabling editing in a table view:
-
tableView:canEditRowAtIndexPath:
-
tableView:commitEditingStyle:forRowAtIndexPath:
When the user taps the edit button, the table view asks its data source which rows are editable by sending the data source a message of tableView:canEditRowAtIndexPath:
. When YES
is returned for a particular index path, the table view instructs the table view cell of the corresponding row that it needs to toggle into or out of edit mode, depending on the table view's edit mode.
In practice, this means that the table view cell shows or hides its editing controls. This concept is best understand by implementing the tableView:canEditRowAtIndexPath:
method as shown below.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { if ([indexPath row] == 1) { return NO; } return YES; }
The above implementation of tableView:canEditRowAtIndexPath:
enables the user to edit every row in the table view with the exception of the second row. Run the application in the iOS Simulator and give it a try.
For the shopping list application, the user needs to be able to edit every row in the table view, which means that tableView:canEditRowAtIndexPath:
should always return YES
as illustrated below.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return YES; }
You may have noticed that nothing happens when you try to delete a row in the table view. The puzzle isn't finished yet. Whenever the user taps the delete button of a row, the table view sends its data source a message of tableView:commitEditingStyle:forRowAtIndexPath:
. The second argument of the corresponding method denotes what type of action the user has performed, inserting or deleting a row. The shopping list application will only provide support for deleting rows from the table view.
Deleting rows from a table view involves:
- deleting the corresponding item from the view controller's
items
property - updating the table view by deleting the corresponding row
Let's inspect the implementation of tableView:commitEditingStyle:forRowAtIndexPath:
. The method starts by checking whether the editing style is equal to UITableViewCellEditingStyleDelete
as we only want to allow the user to delete rows from the table view.
If the editing style is equal to UITableViewCellEditingStyleDelete
, then the corresponding item is removed from the items
array, the corresponding row is deleted from the table view, and the updated list of items is saved to disk.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete Item from Items [self.items removeObjectAtIndex:[indexPath row]]; // Update Table View [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight]; // Save Changes to Disk [self saveItems]; } }
Run the application in the iOS Simulator to test the delete functionality. Don't forget to quit and relaunch the application to verify that items are permanently deleted from the list.
10. Editing Items
We could reuse the TSPAddItemViewController
class for editing items, but reusing a view controller class for both adding and editing items can often overcomplicate the implementation so much that I generally end up creating a separate UIViewController
subclass for editing items. This will initially result in some overlap in terms of implementation and user interface, but it will give us more flexibility down the road.
Creating the Editing View Controller
Create a new UIViewController
subclass and name it TSPEditItemViewController
. The header files of the TSPAddItemViewController
and TSPEditItemViewController
classes are very similar.
#import <UIKit/UIKit.h> @class TSPItem; @protocol TSPEditItemViewControllerDelegate; @interface TSPEditItemViewController : UIViewController @property IBOutlet UITextField *nameTextField; @property IBOutlet UITextField *priceTextField; @property TSPItem *item; @property (weak) id<TSPEditItemViewControllerDelegate> delegate; @end @protocol TSPEditItemViewControllerDelegate <NSObject> - (void)controller:(TSPEditItemViewController *)controller didUpdateItem:(TSPItem *)item; @end
After importing the headers of the UIKit framework, a forward class and protocol declaration is added. The interface of the class is similar to that of theTSPAddItemViewController
class. The main difference is the declaration of a property to store the item that's being edited.
The header file ends with the declaration of theTSPEditItemViewControllerDelegate
protocol. The protocol declaration contains one method that is called when an item is updated. The method accepts the view controller and the updated item as its arguments.
Open the main storyboard, drag a UIViewController
instance from theObject Library, set its class to TSPEditItemViewController
, and create a manual push segue from the list view controller to the edit item view controller, naming it EditItemViewController
.
Drag two UITextField
instances from the Object Library to the view controller's view and position them as shown in the figure below. Select the top text field, open the Attributes Inspector, and enter Name in the Placeholder field. Select the bottom text field and, in the Attributes Inspector, set its placeholder text to Price and setKeyboard to Number Pad. Select the view controller object, open the Connections Inspector, and connect the nameTextField
and priceTextField
outlets to the corresponding text field in the user interface.
In the view controller's viewDidLoad
method, create the save button as we did in theTSPAddItemViewController
class.
- (void)viewDidLoad { [super viewDidLoad]; // Create Save Button self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)]; }
The implementation of the save:
action is very similar to the one we implemented in theTSPAddItemViewController
class. However, there are a few subtle differences that I want to point out.
- (void)save:(id)sender { NSString *name = [self.nameTextField text]; float price = [[self.priceTextField text] floatValue]; // Update Item [self.item setName:name]; [self.item setPrice:price]; // Notify Delegate [self.delegate controller:self didUpdateItem:self.item]; // Pop View Controller [self.navigationController popViewControllerAnimated:YES]; }
Instead of passing the name and price values to the delegate, we directly update the item and pass the updated item to the view controller's delegate. Because the view controller is a child view controller of a navigation controller, we dismiss the view controller by popping it of the navigation stack.
Showing the Edit Item View Controller
In a few minutes, we'll implement the functionality that allows the user to select items from the list view controller to add them to the shopping list. The user will be able to do this by tapping a row in the list view. The question then arises how the user will be able to edit an item if tapping a row is reserved for adding an item to the shopping list?
The UIKit framework provides a detail disclosure button for exactly this use case. A detail disclosure button is a small, blue chevron positioned at the right of a table view cell. To add a detail disclosure button to a table view cell, we need to revisit the tableView:cellForRowAtIndexPath:
method in the list view controller and amend it as shown below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Dequeue Reusable Cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Fetch Item TSPItem *item = [self.items objectAtIndex:[indexPath row]]; // Configure Cell [cell.textLabel setText:[item name]]; [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; return cell; }
Every table view cell has aaccessoryType
property. In the implementation below, we set it toUITableViewCellAccessoryDetailDisclosureButton
. As you may have noticed, the engineers at Apple don't like short names.
How does the table view notify the delegate when the detail disclosure button is tapped? Unsurprisingly, the UITableViewDelegate
protocol defines the tableView:accessoryButtonTappedForRowWithIndexPath:
method for this purpose. Take a look at its implementation.
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { // Fetch Item TSPItem *item = [self.items objectAtIndex:[indexPath row]]; if (item) { // Update Selection [self setSelection:item]; // Perform Segue [self performSegueWithIdentifier:@"EditItemViewController" sender:self]; } }
We fetch the correct item from the items
property and store it in selection
, a private property of the list view controller that we'll declare in a moment. We then perform the segue with identifier EditItemViewController
.
Before we update the implementation ofprepareForSegue:sender:
, we need to declare a private property for storing the selected item.
#import "TSPListViewController.h" #import "TSPItem.h" @interface TSPListViewController () @property NSMutableArray *items; @property TSPItem *selection; @end
We also need to import the header file of the TSPEditItemViewController
class in TSPListViewController.h and conform the TSPListViewController
class to the TSPEditItemViewControllerDelegate
protocol.
#import <UIKit/UIKit.h> #import "TSPAddItemViewController.h" #import "TSPEditItemViewController.h" @interface TSPListViewController : UITableViewController <TSPAddItemViewControllerDelegate, TSPEditItemViewControllerDelegate> @end
The updated implementation of prepareForSegue:sender:
is pretty simple as you can see below. We get a reference to the edit item view controller and set itsdelegate
and item
properties.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"AddItemViewController"]) { // Destination View Controller UINavigationController *nc = (UINavigationController *)segue.destinationViewController; // Fetch Add Item View Controller TSPAddItemViewController *vc = [nc.viewControllers firstObject]; // Set Delegate [vc setDelegate:self]; } else if ([segue.identifier isEqualToString:@"EditItemViewController"]) { // Fetch Edit Item View Controller TSPEditItemViewController *vc = (TSPEditItemViewController *)segue.destinationViewController; // Set Delegate [vc setDelegate:self]; [vc setItem:self.selection]; } }
The implementation of the TSPEditItemViewController
class is almost complete. In its viewDidLoad
method, we populate the text fields with the data of the item
property. Because the setText:
method of a text field only accepts anNSString
instance, we need to wrap the float
value of the item's price
property in a string to display it inpriceTextField
.
- (void)viewDidLoad { [super viewDidLoad]; // Create Save Button self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)]; // Populate Text Fields if (self.item) { [self.nameTextField setText:[self.item name]]; [self.priceTextField setText:[NSString stringWithFormat:@"%f", [self.item price]]]; } }
Adopting the Delegate Protocol
Adopting the TSPEditItemViewControllerDelegate
protocol is limited to implementing the controller:didUpdateItem:
method as shown below. It might surprise you that we don't update the data source of the table view. All we do in the delegate method is reload one row of the table view.
- (void)controller:(TSPEditItemViewController *)controller didUpdateItem:(TSPItem *)item { // Fetch Item for (int i = 0; i < [self.items count]; i++) { TSPItem *anItem = [self.items objectAtIndex:i]; if ([[anItem uuid] isEqualToString:[item uuid]]) { // Update Table View Row NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0]; [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } // Save Items [self saveItems]; }
The reason that we don't need to update the table view's data source, the items
array, is that the updated item was passed by reference to the edit item view controller. In other words, the object that the edit item view controller updated is the same object that is contained in the items
array. This is one of the nice benefits of working with objects and pointers.
Don't forget to save the list of items to make sure the edits are written to disk. Run the application to test the editing functionality.
11. Creating the Shopping List View Controller
Before we explore the data source of the shopping list view controller, let's create some scaffolding to work with. Create a new UITableViewController
subclass and name itTSPShoppingListViewController
.
Open the implementation file of the new class and add two private properties of type NSArray
to the class extension:
-
items
, which will contain the complete list of items -
shoppingList
, which will only contain the items of the shopping list
Since we will be overriding the setter methods of both properties, we have to declare the properties as nonatomic. Don't worry about the exact meaning of this for now.
#import <UIKit/UIKit.h> @interface TSPShoppingListViewController : UITableViewController @property (nonatomic) NSArray *items; @property (nonatomic) NSArray *shoppingList; @end
The idea is to load the list of items every time a change is made to the list and then parse the list of items and extract only those items which have their inShoppingList
property set to YES
. Those items will be added to the shoppingList
array.
Another option would be to store the shopping list in a separate file, but the downside of this approach would be that we have to keep the items in the list view controller and the items in the shopping list synchronized. This is asking for trouble if you ask me.
Custom Setters
The setter methods of items
and shoppingList
will do most of the heavy lifting for us. Take a look at the implementation of setItems:
. Whenever the _items
instance variable is updated (set with a new value), the buildShoppingList
method is called on the view controller.
- (void)setItems:(NSArray *)items { if (_items != items) { _items = items; // Build Shopping List [self buildShoppingList]; } }
Let's see what thebuildShoppingList
method looks like.
- (void)buildShoppingList { NSMutableArray *buffer = [[NSMutableArray alloc] init]; for (int i = 0; i < [self.items count]; i++) { TSPItem *item = [self.items objectAtIndex:i]; if ([item inShoppingList]) { // Add Item to Buffer [buffer addObject:item]; } } // Set Shopping List self.shoppingList = [NSArray arrayWithArray:buffer]; }
ThebuildShoppingList
method populates theshoppingList
array with the items that have theirinShoppingList
property set toYES
. In thebuildShoppingList
method, we create a mutable array to temporarily store the shopping list items. We then iterate through the list of items and add every item to the mutable array that has ainShoppingList
property ofYES
. Finally, we set theshoppingList
property with the contents of the mutable array.
Don't forget to import the header file of theTSPItem
class at the top.
#import "TSPItem.h"
We also override the setShoppingList
setter to reload the table view every time the shoppingList
array is changed or updated.
- (void)setShoppingList:(NSArray *)shoppingList { if (_shoppingList != shoppingList) { _shoppingList = shoppingList; // Reload Table View [self.tableView reloadData]; } }
Displaying the Shopping List
Implementing the methods of the UITableViewDataSource
protocol should be child's play by now. Take a look at the implementation of each method below.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.shoppingList count]; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Dequeue Reusable Cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Fetch Item TSPItem *item = [self.shoppingList objectAtIndex:[indexPath row]]; // Configure Cell [cell.textLabel setText:[item name]]; return cell; }
Don't forget to declare the cell reuse identifier and register the UITableViewCell
class like we've done in the TSPListViewController
class.
@implementation TSPShoppingListViewController static NSString *CellIdentifier = @"Cell Identifier";
- (void)viewDidLoad { [super viewDidLoad]; // Register Class for Cell Reuse [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier]; }
Loading Items
As I explained earlier, the key advantage of using the list of items to store and build the shopping list is that the application stores each item in only one place. This makes updating items in the list and in the shopping list much less of a headache. The loadItems
method is identical to the one we implemented in the TSPListViewController
class.
- (void)loadItems { NSString *filePath = [self pathForItems]; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // self.items = [NSMutableArray arrayWithContentsOfFile:filePath]; self.items = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; } else { self.items = [NSMutableArray array]; } }
Of course, the pathForItems
method is identical as well since we are loading the list of items from the same file as in the TSPListViewController
class.
- (NSString *)pathForItems { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documents = [paths lastObject]; return [documents stringByAppendingPathComponent:@"items.plist"]; }
When you find yourself duplicating code, you should hear an alarm bell ringing. Duplicating code isn't problematic while you're implementing a new feature. Afterwards, however, you should consider refactoring your code to minimize the amount of duplication in the application's code base. This is a very important concept in software development and is often referred to as DRY, Don't Repeat Yourself. Chris Peters wrote a great article on Tuts+ about DRY programming.
Before we put the TSPShoppingListViewController
class to use, we need to update the class's initWithCoder:
method. In addition to setting the title of the view controller, we also load the list of items, which automatically populates the shoppingList
array as we saw earlier.
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { // Set Title self.title = @"Shopping List"; // Load Items [self loadItems]; } return self; }
The final step is to initialize the shopping list view controller by updating the main storyboard. This involves adding a UITableViewController
instance, settings its class to TSPShoppingListViewController
, embedding it in a navigation controller, and creating a relationship segue between the tab bar controller and the navigation controller. Name the segue ShoppingListViewController
. Select the table view of the shopping list view controller and set the number of prototype cells to 0
.
Run the application to see if everything is working properly. Of course, the shopping list is currently empty and we don't have a way to add items to the shopping list. Let's remedy this in the next step.
11. Adding Items to the Shopping List
As I wrote earlier, the idea is to add an item to the shopping list when it is tapped in the list view controller. To improve the user experience, if an item is present in the shopping list, we show a green checkmark to the left of the item's name. If an item that is already in the shopping list is tapped, then it is removed from the shopping list and the green checkmark disappears. This means that we need to take a look at the tableView:didSelectRowAtIndexPath:
method of the UITableViewDelegate
protocol.
Before we implement tableView:didSelectRowAtIndexPath:
, download the source files of this lesson. In the folder named Resources, find the files named checkmark.png and checkmark@2x.png, and add both of these files to the project. We will need them in a few moments.
In the first line of tableView:didSelectRowAtIndexPath:
, we send the table view a message of deselectRowAtIndexPath:animated:
to deselect the row the user tapped. Whenever a row is tapped, it should only be highlighted for an instant hence this addition. Next, we fetch the corresponding item for the selected row and update the inShoppingList
property of the item (YES
becomes NO
and vice versa).
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; // Fetch Item TSPItem *item = [self.items objectAtIndex:[indexPath row]]; // Update Item [item setInShoppingList:![item inShoppingList]]; // Update Cell UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if ([item inShoppingList]) { [cell.imageView setImage:[UIImage imageNamed:@"checkmark"]]; } else { [cell.imageView setImage:nil]; } // Save Items [self saveItems]; }
Based on the value of the item'ssetInShoppingList
property, we either show or hide the green checkmark. We show the checkmark by setting theimage
property of the table view cell'simageView
property. EveryUITableViewCell
instance contains an image view on its left (an instance of theUIImageView
class). By setting the image view'simage
property tonil
, the image view is blank, showing no image.
The implementation oftableView:didSelectRowAtIndexPath:
ends by saving the list of items to disk to make sure that the changes are permanent.
How does the shopping list know when an item in the list view controller is tapped by the user? The shopping list view controller will not update its table view automatically if a change was made to the list of items in the list view controller. In addition, we don't want the list view controller and the shopping list view controller to communicate directly to one another to prevent any form of tight coupling.
One solution to this problem is the use of notifications. Whenever the list view controller makes a change to the list of items, it posts a notification with a specific name to the notification center, an object that manages notifications. Objects that are interested in certain notifications can add themselves as observers of those notifications, which means that they can respond when those notifications are posted to the notification center.
How does all this work? There are three steps:
- the shopping list view controller starts by telling the notification center that it is interested in receiving notifications with a name of
TSPShoppingListDidChangeNotification
- the list view controller posts a notification to the notification center whenever it updates the list of items
- when the shopping list view controller receives the notification from the notification center, it updates its data source and table view in response
Before we implement the three steps I just described, it's a good idea to take a closer look at the NSNotificationCenter
class.
In a nutshell, the NSNotificationCenter
manages the broadcasting of notifications. Objects in an application can register with a notification center to receive notifications using addObserver:selector:name:object:
where
- the first argument is the object that will receive the notifications (the observer)
- the selector is the action that will be triggered when the observer receives the notification
- the name is the name of the notification
- the last argument is the object that sends the notification
If the last argument is set tonil
, the observer receives every notifications with the specified name.
Receiving Notifications
Revisit the initWithCoder:
method of the TSPShoppingListViewController
class and add the view controller instance as an observer to receive notifications with a name ofTSPShoppingListDidChangeNotification
.
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { // Set Title self.title = @"Shopping List"; // Add Observer [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateShoppingList:) name:@"TSPShoppingListDidChangeNotification" object:nil]; } return self; }
The action triggered when the view controller receives a notification with that name is updateShoppingList:
. We set the object
to nil
as it doesn't really matter which object sent the notification.
Before we implement updateShoppingList:
, we need to amend the viewDidLoad
method of the shopping list view controller. In viewDidLoad
, we load the items from disk.
- (void)viewDidLoad { [super viewDidLoad]; // Load Items [self loadItems]; // Register Class for Cell Reuse [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier]; }
Responding to Notifications
The method that is triggered when the observer receives a notification has a specific format as you can see below. It accepts one argument, that is, the notification object which is of type NSNotification
. The notification object keeps a reference to the object that posted the notification and it can also contain a dictionary with additional information. The implementation of the updateShoppingList:
method is quite simple, that is, the loadItems
method is called on the view controller, which means that the list of items is loaded from disk. The rest happens automatically thanks to the custom setter methods that we implemented earlier.
- (void)updateShoppingList:(NSNotification *)notification { // Load Items [self loadItems]; }
Sending Notifications
The third piece of the puzzle is posting a notification whenever the list of items is changed by the list view controller. We can do this in the saveItems
method of theTSPListViewController
class.
- (void)saveItems { NSString *filePath = [self pathForItems]; [NSKeyedArchiver archiveRootObject:self.items toFile:filePath]; // Post Notification [[NSNotificationCenter defaultCenter] postNotificationName:@"TSPShoppingListDidChangeNotification" object:self]; }
We first ask for a reference to the default notification center by callingdefaultCenter
on theNSNotificationCenter
class. Next, we callpostNotificationName:object:
on the default notification center and pass the name of the notification,TSPShoppingListDidChangeNotification
, and the object posting the notification.
Before you build the project, make sure to amend the tableView:cellForRowAtIndexPath:
as shown below to display a green checkmark for items that are already present in the shopping list.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Dequeue Reusable Cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Fetch Item TSPItem *item = [self.items objectAtIndex:[indexPath row]]; // Configure Cell [cell.textLabel setText:[item name]]; [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; // Show/Hide Checkmark if ([item inShoppingList]) { [cell.imageView setImage:[UIImage imageNamed:@"checkmark"]]; } else { [cell.imageView setImage:nil]; } return cell; }
Run the shopping list application to give it a spin. Have you noticed that edits to an item are automatically reflected in the shopping list?
Ready for Publication?
Great. Where is the button to publish the shopping list application to the App Store? We are not quite done yet. Even though we have laid the foundation of the shopping list application, it isn't ready for publication. There are also a few things to consider.
Scalability
The shopping list application is a modest implementation of a shopping list. If the application were to contain hundreds or thousands of items then it would be pertinent to add search capabilities as well as sections to sort the items alphabetically (as we did earlier in this series). It is important to realize that the list of items is written to disk in its entirety every time an item is updated. This is no problem when the list is small, but it will be if the list grows over time to hundreds or thousands of items.
Relationships
Also, users may want to save more than one shopping list. How would you deal with that? One option would be to store each shopping list in a separate file, but how would you deal with changes made to items? Are you going to update every shopping list that contains the item? When you start dealing with relationships, it is better to choose for an SQLite data store. Core Data is an great companion if you choose to go down that road. It is a powerful framework and sports a lot of features that make a lot of the code in our shopping list application obsolete. It is true that Core Data brings a bit more overhead with it so it is key to first consider if Core Data is suitable for your application, in other words, if it is worth the overhead.
Additional Features
There is also a lot of potential for additional features. The price property of the items remains unused in the current implementation of the shopping list application. Also, it would be nice if the user could check off an item from the shopping list by tapping the item. As you can see, the current implementation of the shopping list application is only a modest start.
Conclusion
Even though the shopping list application isn't quite ready for the App Store yet, you can't deny that it works as we planned and it has shown you a lot of new aspects of Cocoa development, such as notifications and implementing a custom delegate protocol.
You now know what to expect from the iOS SDK and what iOS development is like. It is up to you to decide if you want to continue your journey and become a skilled iOS developer. If you do choose to continue with iOS development, then I will provide you with some great resources in next and final installment of this series.
How To Make A Shopping List App Python
Source: https://code.tutsplus.com/articles/building-a-shopping-list-application-from-scratch-part-2--mobile-14127
Posted by: aguilaronoten.blogspot.com
0 Response to "How To Make A Shopping List App Python"
Post a Comment