Your SlideShare is downloading. ×
  • Like
Shopping l ist 2
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Shopping l ist 2


New Shopping List (cont) (an example in code)

New Shopping List (cont) (an example in code)

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. New Shopping List (cont). TN Valley Apple Developers Saturday CodeJam January 8, 2011
  • 2. Last Session • In our last session, we covered adding and deleting items from our shopping list, and saving our shopping list to a persistent data store
  • 3. This Session • In this session, we’re going to cover: • Change our shopping list to add a “quantities” column to our table • Change our data store from NSMutableArray to NSMutableDictionary • Add a ShoppingListItem class to encapsulate our shopping list item-specific code (model object), complete with properties and synthesized accessor methods. • Add a checkbox so we can check purchased items off our list
  • 4. Basic Design Principles • The Cocoa framework has been designed to support applications that follow the Model - View - Controller design principle.
  • 5. Object types • The objects that comprise a Cocoa application should generally fall into one of three types: • Model Objects • View Objects • Controller Objects
  • 6. Model Objects • Objects designed to hold data are Model Objects - Our current Shopping List Application stores each item in an NSString object, which is stored in an NSMutableArray collection
  • 7. View Objects • Objects used to display information on screen are known as View Objects - Our current Shopping List application uses an NSTableView object to display the shopping list items
  • 8. Controller Objects • Objects that handle the interaction between the model objects and the view objects are known as Controller Objects - Our Shopping List application currently has the MyDocument class that serves as the controller object
  • 9. • When the user clicks the Add button (view) the button sends a message to a MyDocument object (controller) • MyDocument (controller) asks the NSTextField object (view) for its value, which it stores in an NSString object • The NSString object is stored in the NSMutableArray object (model) by MyDocument (controller) • MyDocument (controller) sends a message to the NSTableView (view) object instructing it to reload • When reloading, the NSTableView (view) object asks MyDocument (controller) for the number of objects to display. MyDocument, in turn, asks the NSMutableArray (model) object how many shopping list objects it is currently holding, and passes that number to the NSTableView (view) object • The NSTableView (view) object asks MyDocument (controller) for each shopping list item, which MyDocument requests from the NSMutableArray (model) object and passes to the NSTableView (view) object.
  • 10. Reworking the Shopping List Application • We’re going to add the capability to store a quantities column for each item in our shopping list • We’ll redesign our Shopping List application to use an NSDictionary object to store our shopping list items • NSDictionary can store items in a key/value array as opposed to an indexed array used by the NSArray object
  • 11. Interface Builder • First, let’s modify our user interface to display the quantity information in our view, and enable users to specify a quantity when an item is added • Open the MyDocument.xib file in Interface Builder
  • 12. Click on the Table View object, switch to the Attributes Inspector, and increase the number of columns to 2
  • 13. Click and drag the new column in the list above the existing column. Use the Attributes Inspector the change the title to “Quantity”, and the Size Inspector the widen the column to “60”
  • 14. Add a label and a text field to the user interface to enable the user to specify a quantity when a new shopping list item is added. Save everything in Interface Builder and switch to Xcode.
  • 15. Open the MyDocument.h file and add an IBOutlet for the new quantity text field, and one for each of the columns in the view table. Save and switch back to Interface Builder.
  • 16. Wire up the quantityColumn Outlet to the Quantity Column, the itemNameColumn Outlet to the Shopping list Items Column, and the newItemQuantityTextField Outlet to the Quantity text field. Save and switch to Xcode.
  • 17. Make the following changes to the init method:
  • 18. • The NSMutableArray object is allocated and initialized, and each item is added to the array as an autoreleased NSDictionary object, complete with a name (itemNameKey) and a quantity (itemQuantityKey). • Why autoreleased? Once each object is added to the NSMutableArray object, it is retained as long is it is a member of NSMutableArray; if an NSDictionary object is removed from the array, or the NSMutableArray object is deallocated, then the NSDictionary object removed, or belonging to the deallocated array, will be released as well.
  • 19. Make the following changes to the tableView:objectValueForTableColumn:row: method: Build and run the Shopping List application to make sure it is displaying our initial shopping list contents. Note: We still need to modify the methods to add or edit shopping list items
  • 20. Make the following changes to the tableView:setObjectValue:forTableColumn:row: method Save your code, then Build and Run. You should be able to edit any items (name or quantity) in the shopping list.
  • 21. Note the following lines of code: The quantity is stored in the NSDictionary object as an integer value; however, the Table View object converts the integer value to a string value before displaying. We need to convert any edited numeric value in the Table View back to an integer value before we store the data in the NSDictionary object again. We have one final change to make to add items to our list.
  • 22. Make the following change to the addNewItemToShoppingList: method: Note that we’ve simplified this method somewhat; there is no check for duplicate items, and this code does not empty the text fields in the user form. You can download the source code from the publisher’s website and look at the source for chapter 11; you will see one possible implementation that does this. Build and Run!
  • 23. Encapsulation: ShoppingListItem Class • In programming, encapsulation refers to: - the process of restricting access to an object’s components - the process of bundling data with methods operating on that data • We’re going to refactor our shopping list application to encapsulate the code for our shopping list items into a single class, the ShoppingListItem class.
  • 24. • In Xcode, create a new Objective-C class, inheriting from NSObject, and name it “ShoppingListItem”; make sure you generate the header (.h) file. • The ShoppingListItem needs to store an item’s name and quantity • The ShoppingListItem class defines a “model” object.
  • 25. Only one of these items is an object (itemName). Since both the itemName and quantity instance variables need to exist for the life of a ShoppingListItem object, we need to allocate and initialize the itemName object variable in an init method, and release it in dealloc. We’re going to create two initialization methods: our basic init method, and a specialty initialization method called initWithName:quantity:. We’re also going to create a convenience method called shoppingListItemWithName:quantity:.
  • 26. Switch to the ShoppingListItem.m file, and implement the following methods:
  • 27. Encapsulation: Protecting data • To protect instance variables from manipulation by external objects, an object should provide accessor methods for those values. Accessor methods let you provide a publicly accessible interface to external objects to retrieve and set data contained in instance variables without directly accessing those variables. • An example of why you would want to do this would be to conduct some data validation techniques on the data to be stored in an instance variable.
  • 28. Accessor methods: Objective-C 2.0 • With version 2.0, Objective-C provides a compiler directive that creates proper accessor methods for instance variables: @property and @synthesize • @property (keyword) object-type object- name (used in the interface) • @synthesize object-name (used in the implementation)
  • 29. Make the following changes to the interface file: and the implementation file:
  • 30. • @property (nonatomic, retain) NSString *itemName is the equivalent of declaring a setter method called setItemName: that releases any existing objects in the instance variable, and creates and retains a new NSString object in the instance variable initialized with the value provided, and a getter method called itemName: that returns the NSString object stored in the itemName instance variable.
  • 31. Now it’s time to refactor our Shopping List Application again, to use our newly created ShoppingListItem object.
  • 32. Save any unsaved files, and switch to MyDocument.m to make the following changes:
  • 33. • Build and Run! • You’ll find that your shopping list application works as before EXCEPT you cannot save a shopping list. Since we’re now working with a custom model object, we’ll have to write methods for that object to save and open saved shopping lists, which we’ll do later. • Now, we’re going to add the capability to check an item off our list
  • 34. Open the ShoppingListItem.h file in Xcode, and make the following changes: Switch to the implementation file and make the following changes: Save these changes, and open the MyDocument.xib file in Interface Builder.
  • 35. • Using the same methodology we used earlier, add an extra column to the user interface called “Purchased”. Use the Library Palette to find a Check Box Cell and drag and drop it onto the newly created column -- you’ll see the “Text Cell” object will be replaced with a check box. • Use the Check Box’s Attribute Inspector to set the Position value to the second selection – the one that’s just a square but no line. You’ll see the user interface shows only a checkbox but not the word “Check”. • Save and toggle back to Xcode to add an outlet.
  • 36. Save these changes and toggle back to Interface Builder to wire up the Checkbox column with the IBOutlet. Once this is done, save MyDocument.xib in Interface Builder and toggle back to Xcode.
  • 37. Make the following changes to the MyDocument implementation file:
  • 38. Saving our Shopping List • When we changed our Shopping list to encapsulate the functionality of the Shopping List Item within a separate object, we lost the ability to use NSArray’s writetoUrl methods since any objects it is saving must be an array, a dictionary, or objects that can be converted to strings. • We need to utilize a class available in Cocoa to serialize our Shopping list items so they can be saved to disk. • This class is called NSKeyedArchiver
  • 39. NSKeyedArchiver • NSKeyedArchiver provides the ability to archive objects to disk using string keys. • If you look at the documentation for NSKeyedArchiver, you’ll see a convenience class method called: + archiveRootObject:toFile: • This method accepts an object that forms the top root of a heirarchy of objects – which in our case is the shoppingListArray instance variable
  • 40. NSKeyedArchiver • The objects archived by NSKeyedArchiver must conform to the NSCoding protocol, which NSMutableArray (shoppingListArray) does. • However, the ShoppingListItem class, which makes up each object in the shoppingListArray, does not • We need to modify the ShoppingListItem class to implement the NSCoding Protocol.
  • 41. NSCoding Protocol • The NSCoding Protocol requires that any class implementing it must implement two methods: - (id)initWithCoder:(NSCoder *)aDecoder - (void)encodeWithCoder:(NSCoder *)aCoder
  • 42. Constants • Sine we’ll be working with keys again, and we want to make sure we use the same key to decode archived information that we used to encode it, we’ll set up some constants to hold our string keys
  • 43. Add the following to the ShoppingListItem implementation file: Implement the encodeWithCoder: method Implement the initWithCoder: method
  • 44. To utilize these methods, we need to change our writing and reading methods in MyDocument. Open the MyDocument implementation file and make the following changes: Build and run!
  • 45. • This concludes the major topics we needed to cover in Beginning Mac Programming to give us a broad overview of Objective-C and Cocoa. • We are now ready to dive into iOS Programming!!!!
  • 46. As of today, the book we’ve chosen: • Beginning iPhone 4 Development: Exploring the iOS SDK (Apress Publishers) by David Mark, Jack Nutting, Jeff LaMarche has not yet published, although it is scheduled to publish this month. As soon as the eBook becomes available I will send out a message through the Meetup mailing list with information on purchasing the book using our negotiated group discount, which I will provide to everyone once I get the details from Apress. If the book has not published by our next meeting, I will have material prepared to get us started!
  • 47. A Reminder!!! • For our next meeting: • Send me your email address so I can invite you to a DropBox shared folder that I’ll be using to share code: • Go ahead and register on GitHub for an account (I’ll cover this later, but we’ll eventually be using GitHub as there is support included in the upcoming Xcode4 for it) • If you haven’t done so, upgrade your Xcode version to Xcode 3.2.5 / iOS 4.2 • Register as an Apple Developer (free) • Change your account settings on Meetup to receive mailing list communications
  • 48. Later this year…. • Plan to upgrade to iOS Developer status (requires $99/year fee) later this spring • This is required to be able to deploy code for development, testing and production to an iOS device • If you don’t have one, plan to get an iOS device (3rd or 4th generation iPod Touch, iPhone 3GS/iPhone4, iPad) this spring