Published on

Slides for a presentation on iOS that I gave at the fall 2012 Near Infinity conference. Links to the sample applications on GitHub are in the slides.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. iOS Scott Leberknight
  2. 2. The Big Picture Patterns Languages APIs Tools
  3. 3. Patterns MVC(S) Delegation ProtocolsNotificationsTarget-Action
  4. 4. LanguagesObjective-C C(lower-level APIs)
  5. 5. APIsCore UIKit Foundation Core GraphicsLots more... MapKit Core Location OpenGLCore Data GameKit Social Accounts ...
  6. 6. Tools XCode
  7. 7. Tools Interface Builder
  8. 8. First App* Delegation MVC Target-Action*
  9. 9. Model@property (nonatomic, copy) NSArray *fortunes; FOViewController.h
  10. 10. View Outlets & ActionsFOViewController.xib
  11. 11. Outletsin XCode... FOViewController.h
  12. 12. Outlets in IB... FOViewController.xib
  13. 13. Target-Action Target - File’s OwnerAction - “touch up inside” (our view controller)
  14. 14. Controller#import <UIKit/UIKit.h>@interface FOViewController : UIViewController// Model@property (nonatomic, copy) NSArray *fortunes;// Outlets@property (nonatomic, strong) IBOutlet UITextView *fortuneField;// Actions- (IBAction)showFortune:(id)sender;@end words allow (IBOutlet & IBAction key ilder) connections in Interface Bu FOViewController.h
  15. 15. Controller#import "FOViewController.h"@implementation FOViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { _fortunes = @[ @"A dubious friend may be an enemy in camouflage.", @"A feather in the hand is better than a bird in the air.", @"A friend asks only for your time not your money.", // ... ]; } return self;}- (IBAction)showFortune:(id)sender { int fortuneIndex = arc4random() % [_fortunes count]; NSLog(@"fortuneIndex: %d", fortuneIndex); NSString *fortune = [_fortunes objectAtIndex:fortuneIndex]; [_fortuneField setText:fortune];}@end FOViewController.m
  16. 16. Delegation#import <UIKit/UIKit.h>// Inherits from UIResponder// Conforms to UIApplicationDelegate protocol@interface FOAppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@end FOAppDelegate.h
  17. 17. Delegation#import "FOAppDelegate.h"#import "FOViewController.h"@implementation FOAppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Create our view controller; set it as the root view controller FOViewController *viewController = [[FOViewController alloc] initWithNibName:@"FOViewController" bundle:nil]; [[self window] setRootViewController:viewController]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES;}@end FOAppDelegate.m
  18. 18. Run It!1. Load view controllerin App Delegate2. Tap “Get Fortune!”3. showFortune: called4. Get fortune from model5. Call setText: on UITextView
  19. 19. Objective-C Object-oriented (layered on top of C) Single-inheritanceProtocols (like Java interfaces) Message sending
  20. 20. Objective-C (continued) Properties Blocks (like closures) SelectorsARC (automatic reference counting) GCD (Grand Central Dispatch)
  21. 21. Properties@property (nonatomic, strong) IBOutlet UITextView *fortuneField; * Modifiers determine threading and storage model * IBOutlet indicates it can be an outlet to IB * Compiler generates: - instance variable _fortuneField - getter method fortuneField - setter method setFortuneField
  22. 22. Sending Messages selector[detailViewController setItem:newItem]; receiver argument
  23. 23. Sending Messagesreceiver[self presentViewController:navigationController animated:YES completion:nil]; selector arguments
  24. 24. Creating ObjectsWLItemsViewController *itemsViewController = [[WLItemsViewController alloc] init]; initialize allocate object memory
  25. 25. Blocksint amountToAdd = 7;int (^adder)(int) = ^(int num) { return num + amountToAdd;};NSLog(@"%d", adder(3));// prints "10" to XCode console
  26. 26. Blocks - inline[detailViewController setDismissBlock:^{ [[self tableView] reloadData];}]; [self tableView] is captured from scope defining block!
  27. 27. Objective-C really is an OK language, once you get used to its quirks, and it keeps improving...
  28. 28. Core APIs UIKit FoundationCore Graphics
  29. 29. UIKit“The UIKit framework provides the classes needed toconstruct and manage an application’s user interface for iOS.It provides an application object, event handling, drawing model,windows, views, and controls specifically designed for a touchscreen interface.”
  30. 30. UIKit & Grand Central Dispatch"For the most part, UIKit classes should be used only from anapplication’s main thread. This is particularly true for classesderived from UIResponder or that involve manipulating yourapplication’s user interface in any way." Introduction/Introduction.html#//apple_ref/doc/uid/TP40006955-CH1-SW1
  31. 31. Update UI using GCD-(void)handleIncoming:(NSData *)data{ dispatch_async(dispatch_get_main_queue(), ^{ // Retrieve data... // Update the UI using UIKit methods... });}
  32. 32. Foundation “The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language.”
  33. 33. Core Graphics “The Core Graphics framework is a C-based API that is based on the Quartz advanced drawing engine. It provides low- level, lightweight 2D rendering with unmatched output fidelity. You use this framework to handle path-based drawing, transformations, color management, offscreen rendering, patterns, gradients and shadings, image data management, image creation, masking, and PDF document creation, display, and parsing.”
  34. 34. Many, Many More APIsCore Location MapKit Quartz Core AnimationCore Motion AdSupport...
  35. 35. Sample Application - Wishlist * Displays list of items Move and delete items in list Detail view to create/edit items Choose images for items *
  36. 36. List of items Editing list
  37. 37. Add/edit item Choose image
  38. 38. PatternsMVC(S): Model, View, Controller (, Store) “Store” is like a DAO (data access object) Extract store logic from controllers
  39. 39. PatternsInheritance - e.g. table view controllerDelegation - e.g. image picker delegateNotification - e.g. low-memory warning
  40. 40. Model - WLItem#import <Foundation/Foundation.h>@interface WLItem : NSObject <NSCoding>-(id)initWithItemName:(NSString *)name;-(id)initWithItemName:(NSString *)name occasion:(NSString *)occasion store:(NSString *)store price:(int)price;@property (nonatomic, strong) WLItem *containedItem;@property (nonatomic, weak) WLItem *container;@property (nonatomic, copy) NSString *itemName;@property (nonatomic, copy) NSString *occasion;@property (nonatomic, copy) NSString *store;@property (nonatomic, assign) int price;@property (nonatomic, copy) NSString *imageKey;@property (readonly, nonatomic, copy) NSDate *dateCreated;@property (nonatomic, copy) NSDate *dateModified;@end
  41. 41. ViewsUITableView (presents list of items) * Not defined in XIB * App delegate creates table view controller programmatically within a navigation controller * Edit and + buttons defined in code
  42. 42. Views Detail View Controller
  43. 43. ControllersWLItemsViewController: Subclass of: UITableViewController Conforms to: UITableViewDelegate UITableViewDataSource Responsible for creating table view cells Manages moving/deleting items Uses UINavigationController to present detail view controller for adding/editing items
  44. 44. ControllersWLDetailViewController: Subclass of: UIViewController Conforms to: UITextFieldDelegate UINavigationControllerDelegate UIImagePickerControllerDelegate UIPopoverControllerDelegate Responsible for loading/saving items & images Manages image picking controllers Manages text changed notifications
  45. 45. StoresWLItemStore Stores WLItem objectsWLImageStore Stores UIImage objects
  46. 46. Application Flow
  47. 47. WLAppDelegateapplication:didFinishLaunchingWithOptions - Create a WLItemsViewController - Create a UINavigationController - Embed WLItemsViewController in UINavigationControllerWLItemsViewControllerviewWillAppear: loads table viewList editing UI is automatic whenadd button using editBarButtonTap + button, fires addNewItem: whichpresents detail view controller
  48. 48. WLDetailViewController init: createsCancel & Done bar button itemsviewDidLoad: sets background colorviewWillAppear:animated: - Sets up form for editing/adding item - Display image if present - Register for text change notificationsdone: dismisses controller,completion handler reloads table dataviewWillDisappear: saves item data
  49. 49. Tapping camera buttoninvokes takePicture:UIImagePickerControllerpresents camera or picturelibraryUIImagePickerControllerdelegate (controller) handlesselected image
  50. 50. imagePickerController:didFinishPickingMediaWithInforetrieves selected image, stores it,and displays itUse Core Graphics to add a borderaround imageUse Quartz to add a shadow aroundimage
  51. 51. UITextFieldDelegate methodtextFieldShouldReturn:dismisses keyboard whenreturn tappedUIControlEventEditingChangedevents trigger selectortextChanged: which addsmodified date when editingexisting items
  52. 52. On iPad use a UIPopoverController for selecting images
  53. 53. UIPopoverController was used to select the delicious image...
  54. 54. One more thing...
  55. 55. Storyboards (an alternative way to define app flow)
  56. 56. SummaryPatterns, Languages, APIs, Tools MVC(S), Delegation, Protocols Objective-CLots of APIs to use (and learn)XCode / Interface Builder (IB)Connect outlets & actions in IB
  57. 57. References
  58. 58. Sample Code Fortunes: Wishlist:
  59. 59. My Infoscott.leberknight at