Friday, 2 May 2014

Post WDI - iOS Development Device Deployed App (Memory Leaks, MVC, Custom Methods, Forward Declarations, Fluid Imaging, Animations, Sensors, Testing, Debugging, Deployment)

Activities @ TeamTreeHouse - 

iOS Development (using Xcode 5 IDE) with Douglass Turner & Amit Bijlani (Cont'd)

DONE Building First iPhone App (Beyond the Basics)
  • Primative Data (Scalar) Types (Fixed memory size allocated by compiler depending on type automatically) { char %c, unsigned int %u, long %ld, float %f, double %lf }
  • Pointers (Dynamic Memory with variable storage) 
    • Memory Address %p  i.e. printf("%p", &i);
    • Mitigates "Passing by Value" Issues (instead of allocate mem twice for same data which is resource intensive, store value in only one place and pass pointer)  i.e. int i = 100; incrememt(int *x); int *i; // i outputs mem addr
  • Arrays
    • Inherit from NSObject (all objects do, it allows mem handling and access to runtime) creates list of string objects accessible with objectAtIndex
    • Example 1: int primts[3]; // store 3 no's. points mem addr 0 plus offset
    • Example 2: // equivalents
Alloc and Init Method
NSNumber *number; // declare varnumber = [NSNumber alloc]; // alloc mem add for object[number initWithInt:100]; // init mem w value using convenience method
Refactored EquivalentNSNumber *number = [[NSNumber alloc] initWithInt:100]; // equivalent to above three lines
Literal Shorthand Equivalent (iOS7 more readable and maintainable)NSNumber *oneHundred = @100; // alloc and init behind the scenes[NSNumber numberWithInt:100];
  • C Language Equivalents
  • Property Attributes (of Classes)
    • @  
      • Compiler Directive (highlights shorthand notation in Objective-C)
      • Examples: @"" (NSString), @100 (NSNumber), @[ ] (NSArray), @{ } (NSDictionary)
    • @property   (i.e. @property (nonatomic, strong) NSString *title;)
      • Uses: Declaration sets up getter and setter methods so can set and get instance vars encapsulated in custom classes, and so objects are available in all methods and may be used with 'self' instance of the View Controller (otherwise cannot get access as out of scope)  i.e. self.vehicles = [[NSArray alloc initWithObjects ...
      • Strong (reference) { retain object/property }
      • Weak (reference) { no concerned if underlying property deallocated and used for child in parent child relationships } 
      • Retain { used in previous versions before AFC when had to maintain retain counts)
      • AFC { Automatic Reference Counting)
      • Retain Count { retain count of 1 means only one object pointing to mem location (i.e. after alloc and init one custom class), whilst retain count of 2 means two objects pointing to same mem location until pointer set to nil }
      • Retain Count Logging { NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)title)); }
      • Deallocate { when no objects pointing to mem addr can deallocate }
      • Nonatomic { non multi-threaded apps where only one process reading or writing at any time }
      • Atomic { multi-threaded apps where multiple processes point to same mem locations and prioritiation of access to data or locking }
  • Memory Leaks
.h (header)@interface Vehicle : NSObject;@property (nonatomic, strong) id wheel;
.m (implementation)Vehicle *vehicle1 = [[Vehicle alloc] init];vehicle1.wheel = vehicle1; // 'wheel' is child property of vehicle1 pointing to its parent creating a 'retain' cyclevehicle1 = nil; // deallocated vehicle1 but 'wheel' is still pointing to vehicle1 and not released causing memory leak
  • Scoping and Self { declare delegates pointing to self when creating a delegate property. use 'self' to implement methods as part of Delegate Protocol }
  • Help and Sample Code { Help > Documentation and API Reference }
  • AppDelegate { helps hook into events of app lifecycle. not used for simple app (move to Support Files) }
  • Interface .h { defines methods and properties of class }
  • Implementation .m { implements methods of interface }
  • Communication and Connections { Code communicates with View Controller and Storyboard View elements connect with IBAction }
  • Target-Action Design Pattern { where target is View Controller and action is method created triggered by IBAction connection }
  • Shortcuts 
    • CMD+0 (Navigator show/hide)
    • CMD+R (Compiles program)
    • CMD+? (Help menu)
      • + .... <method>  { Class Methods that can be directly called on the Class }
      • - .... <method> { Instance Methods called directly on instance variables }
      • [ ...  { code for Method Calls / send a msg to Class }
      • ^{ }   { code denoted with carat denotes passing in a Code Block }
    • CTRL+Click+Drag (places controls relative to other control)
    • CMD+Click { shows class header info }
    • OPT+Click { shows info about class }
    • CMD+ ~ { switches between Xcode and Reference Docs }
  • UIView { belong to each View layer with a property NSArray of 'subViews' and contain added control elements within bounds }
  • Window { main View Controller attaches View to Window on launch of app }
  • UIViewController { manages resizing, layouts, interactions, events, coordination with data, lifecycle events upon load and unload of views }
    • viewDidLoad
    • viewWillAppear
    • viewWillDisappear
    • viewDidUnload
  • UIView Class { rectangular area defined by Frame property of type CGRect with size, origin, and Struct properties }
  • Randomisation { pseudo random numbers generator function arc4random_uniform(max_number) }
  • MVC (Model-View-Controller) Convention 
    • Benefits: design pattern following Single Responsibility Principle allows reuse of Model for multiple View Controllers, and custom models allow use of 'readonly' data to control format and prevent vulnerabilities
    • View (IB aka Storyboard)
    • Controller { View Controller class responsible for retrieving and displaying data on the View. Shift any data (i.e. NSArray) to the Model to achieve MVC design pattern }
    • Model { responsible for storing and providing data. data should be moved to its own class } 
  • Custom Getter and Setter Methods using Hidden Methods
    • Example
@property (strong, nonatomic) NSArray *vehicles; // declaration creates instance var with same name prefixed with underscore (hidden) providing access to this vars value using getters and setters
@interface LSCarYard:NSObject { // object with '_vehicles' as hidden instance var created by @property NSArray *_vehicles; }
// getter method (get is implied) would return an array object -(NSArray*) vehicles;
// setter method (takes Array object as argument) -(void) setVehicles: (NSArray*) newVehicles;
// alloc and initLSCarYard *caryard = [LSCarYard alloc] init];
// get object by calling the 'vehicles' method and returning the _vehicles instance variableNSArray *array = carYard.vehicles; // use dot notation to access object properties
// assign a new array setter by calling setVehicles method to set the value of _vehicles instance varcarYard.vehicles = array;
  • Forward Declarations { @class instructs header of class that a class exists but will be imported in the implementation file instead of the header (not good practice to import local classes within the @interface) }
  • Protect with ReadOnly Attribute (Data Traceability and Scalability)
    • Use: avoids overriding elements accidently (i.e. @property (strong, nonatomic, readonly) ...)
  • Images (images.xcassets)
    • Display Image Options
      • Image View Control 
      • UIImageView { insertSubview atIndex (i.e. background at 0) provides layer insertion flexibility versus just using 'addSubview' }
    • View Hierarchy drag-and-drop to modify layer in which they are displayed 
    • Device Displays 
      • Points Coordinate System { consistency across device resolutions }
      • Auto-Layout { responsive apps for different form factors }
      • Form Factor Toggle { 3.5 inch, 4 inch, device, etc } 
      • Constraints and Pins (Bridging and Validation) { points from bounds of screen to maintain height and width }
      • Fluid Resizing { fixes distorted image fill to fit flush }
      • Retina (2x) has 326 pixels per inch (PPI) for 3.5 inch display and is a high res image with high pixels in small area (not necessarily scaled)
    • Button States { normal (OFF), highlighted (ON), selected }
    • Relative Controls
      • Shortcuts {CTRL+Click+Drag (places controls relative to other control) }
  • Image Based Animation (rapid sequence of images measured in FPS creates illusion of motion)
    • UIImageView { array of UIImage objects (both normal and retina) for an animation }
  • Property Based Animation { using Alpha property for semi-transparency accompanied by animation code to create fading appearance }
  • Intercepting Motion Events (Animations)
    • Sensors 
      • Accelerometer (detects acceleration or speed)
      • Gyroscope (detects rotation events)
    • Events and Actions
      • Shake { captures acceleration and rotation along x, y, z, where constant for this motion is UIEventSubtypeMotionShake }
      • UIResponder is parent class and grandfathers methods including
        • motionBegan
        • motionEnded
        • motionCancelled
      • Simulate Motion Events { Menu > Hardware > <select gesture> }
  • Pragma Marks { directives that appear in Xcode menus to expedite access to methods }
    • #pragma mark - { used to categorise methods by creating a line between them in the Breadcrumb Navigation area }
  • DRY (Don't Repeat Yourself) Principle { refactor and organise code so repetitive tasks are shifted into and called from new methods to comply }
  • Sounds 
    • AudioToolBox Framework manual installation (does not automatically locate) into the Main Bundle using NSBundle path for resources to load sound
  • Testing, Debugging, and Device Deployment (built-in debugger)
    • Debug Navigator { compressing or decompressing the thread list with lower bar }
    • Debug Bar (toggle break points, step over and into)
    • Console
    • main.m (Supporting File in C)
    • Line Numbers (turning them ON)
    • Exception (Dynamic) Breakpoints 
    • Multiple Breakpoints (using Gutter)
    • UINib { View that the compiler creates from the Storyboard }
    • Orphaned Connections { IBOutlets in Connections Inspector no longer used }
  • App Icon and Launch Images 
    • Note: SystemUI automatically crops corners for display in Spotlight (first screen on iPhone when search for apps)
    • Points { standard size for non-retina iPhone, and 2x means twice the amount of points in pixels (i.e. 60 for 2x translates to 120x120 pixels) } 
  • App Store Configuration
    • Help > "app-related" (search)

Sunday, 27 April 2014

Post WDI - iPhone App Sandbox, Data Management Persistence Mechanisms (Object Archiving, Core Data to SQLite)

iPhone Development (Xcode 5) (Cont'd)

iPhone App Sandbox and Data Management  DONE
  • Application Sandbox { restrictions (policy and technical) introduced by Apple to protect users from malicious apps harming their devices, and where all apps exist in a sandbox. violation cause for app rejection from App Store }
  • Object Archiving 
    • Object Graph { all references between interlinked web of objects in memory. used for Cocoa's Object Archiving (serialisation mechanism) where the object graph is stored to the file system and unarchived and read it back into memory to restore a session at the same point. Object Archiving Components include NSCoder object and NSCoding Protocol }
      • NSCoder { encode and decode archiving any object to NSCoding Protocol using "keyed encoding" where a key is provided for each instance var }
      • NSCoding Protocol 
      • Methods: 
        • initWithCoder { Decoding where key is provided and decoded instance var returned } 
        • encodeWithCoder { Encode all instance vars (using encodeObject:forKey, encodeInt:forKey, encodeBool:forKey, encodeDouble:forKey, encodeBytes:forKey) of object to store during archival. implemented with decision on instance vars of scalar type to encode or not encode (transient) } 
    • Archiving to File
      • archiveRootObject:toFile of NSKeyedArchiver (on applicationWillTerminate event)
    • Unarchiving from File
      • unarchiveObjectWithFile method from NSKeyedUnarchiver(on viewDidLoad event)
    • Data Storage Options
      • Library/Preferences Directory { access indirectly with NSUserDefaults API }
      • Library/Caches Directory { direct file manipulation, cache retrieved data, persists between launches, improves performance }
      • Documents Directory { direct file manipulation, main location to store, backed up when synced }
      • tmp Directory { direct file manipulation outside devices limited volatile memory without persisting between launches of app }
    • File Paths 
      • NSSearchPathForDirectoriesInDomains { Core Foundation function returns multiple directories in NSArray with NSStrings extracted with objectAtIndex }
      • stringByAppendingPathComponent { joins path fragments }
    • Interface Elements
      • Flexible Space Bar Button
  • Core Data 
    • Dfn: Object-Relational Mapping (ORM) framework (handles conversion of data to and from objects in the app and relational data in a database) providing management and persistence of in-memory object graphs comprising multi-level undo management, data validation, data consistency across independent data accessors, efficient filtering with indexing, sorting, and searching object graphs, and persistence between invocations to various data repositories 
    • Uses: wraps the SQLite database and relational database (alternative to using SQL and SQLite API directly) to perform querying and data management functions of CRUD (create, read, update, delete)
    • Alternatives to SQLite Repository 
      • Uses: Core Data features (undo support, object schema versioning) without need for relational databases
      • Binary File Format { same limits on large data sets as Object Archiving }
      • In-Memory Implementation { no persistence between app invocations }
    • Concepts of Core Data
      • Managed Object Context { subset of persistent objects used by app at a point in time and containing the object graph. Core Data notices changes to the objects and persists changes to the database when save is called }
      • Managed Object { object managed by Core Data that can be added or removed from object graph resulting in Core Data performing inserts and deletes w database. changes to attributes and relationships of managed objects results in Core Data performing update operations to database }
      • Managed Object Model { object-relational schema, description of Entities persisted via Core Data. it's a mapping between an object in Objective-C and an Entity as it will be stored as rows in a database table in SQLite }
        • Xcode Data Modelling Tool { for .xcdatamodel files }
      • Entity 
        • Dfn: model of managed object containing only parts of object that Core Data will be persisting
        • Model Types:
          • Object Attributes { for persisting }
          • Relationships and Other Entities { stored to form a persistent object graph }
      • Persistent Stack { parts of Core Data that interact with a data repository like SQLite }
    • Core Data Application Template 
      • Dfn: boilerplate code that contains additional properties and actions to allow the Core Data application to interact with the managed object context through its application delegate 
      • Features:
        • @dynamic construct { tells compiler missing property getters and setters in implementation file will be provided by superclass NSManagedObject at runtime } 
        • managedObjectContext property { Core Data managed object context for passing to controllers subview in the app window upon applicationDidFinishLaunching }
      • CRUD (Create, Read, Update, Delete)
        • insertNewObjectForEntityForName:inManagedObjectContext method of NSEntityDescription { Create. arguments include name of Entity NSString from managed object model, and reference to managed object context }
        • NSFetchRequest instance in viewDidLoad method { Fetch. with NSEntityDescription to specify type of Entity to fetch, returns NSMutableArray of managed objects
        • hasChanges used by managed object context to report any changes to managed objects that were tracked and save in the applicationWillTerminate method 
        • deleteObject method of NSManagedObjectContext is passed managed object to delete
        • Note: NSUInteger vs NSNumber (scalar integer vs actual object)
Curiosity:



Links:

Post WDI - iPhone Storing App Preferences

iPhone Development (Xcode 5) (Cont'd)

iPhone Storing App Preferences   DONE
  • Application Preferences (aka Settings, User Defaults, User Preferences, Options)
    • Overall preference system where apps customise for users
  • Application Preferences System { low-level tasks of persisting preferences to iPhone with app preferences separate and backed up  
  • Design Principles
    • Opinionated Software { limit app preferences with an opinion on best ways to accomplish tasks serves larger market } 
    • Implicit (In-App) Preference Exposure { based on user actions using the app and returning to last state of app upon reuse }
    • Explicit Preference Exposure using Apples Settings Application { single location to customise iPhone Settings Bundle, but UI is limited }
    • Alternatively { customized toolbar with limited frequently used items and a 'more' button }
    • Examples { API access, streamline w default inputs saved to reduce user taps }
  • Utility App Template { contain info icon that animates a transition to a flipside view for setting app preferences when tapped }
  • Settings Bundle Template { generated from Resources group in sidebar it creates a Root.plist file editable in Property List Editor, which controls appearance of the app in the settings bundle where preferences may be set and retrieved from the preferences database and grouped. types may be edited (i.e. PSTextFieldSpecifier changed to PSMultiValueSpecifier). note that multiple PList files may be created (i.e. About, etc) }
  • Reading and Writing User Defaults
    • NSUserDefaults API { singleton pattern (only one instance object of class stored) class used to store app preferences as key/value pairs }
    • viewWillDissappear event { persist in saving key values when view disappears  (i.e. on/off state and levels as constants) using setBool and setFloat methods of standardUserDefaults method  associated with NSUserDefault singleton API. preferences stored in PList file (XML property list file) }
    • viewDidLoad event { read and use preferences when view appears upon application launch using floatForKey and boolForKey methods of NSUserDefaults API. set the preferences with a Helper Method setValuesFromPreferences, and cover the initial case with default settings using a dictionary of default preference keys and values to the registerDefaults method. Array Title String properties and Array of UITextFields setup by reading preferences current value from NSUserDefaults, and used for storage and editing. Store preferences into user defaults database using Utility Template App 'done' action instance }
  • In-App Preferences
    • FlipSideViewController (to implement table view Delegate and Data Source Protocols instead of using TableViewController) for Utility Template App (with Flipside View) 
      • Preferences Stored and Edited { added as subviews of table cells content view }
Links:

Post WDI - iPhone Multiview Navigation-Based Apps (Table View Categories)

iPhone Development (Xcode 5) (Cont'd)

iPhone Multiview Navigation-Based Apps (with Table Views)    DONE
  • Table Views { toolset to display list of cells onscreen by Category and Sub Category, they respond to touch events and allowing users to scroll up and down, with each single cell structured to contain multiple pieces of info, and cells broken into sections of info clusters }
    • Types
      • Plain (aka Index Tables) { lack visual separation of sections of grouped tables
      • Grouped 
    • Implementation
      • UITableView { instance creates table view }
        • Methods:
        • accessoryType ("disclosure indicator" array. touching reveals details)
      • UITableViewController { subclass instance handles interactions with table view and conforms to req'd protocols }
      • UITableViewDataSource Protocol { provide data for table to display } 
        • Methods: 
        • numberOfSectionsInTableView (qty table sections)
        • tableView:tableViewNumberOfRowsInSection (qty rows in each section)
      • UITableViewDelegate Protocol { creating cells in table and react to user selection }
        • Methods:
        • tableView:titleForHeaderInSection (string title section no.)
        • tableView:cellForRowAtIndexPath (returns UITableViewCell object for table section and row)
        • tableView:didSelectRowAtIndexPath { react to row touch event from user using indexPath instance }
      • NSIndexPath { communicates row and section info (IndexPath for incoming objects in table methods with accessors IndexPath.section and IndexPath.row }
        • Methods:
        • UILabel object { textLabel, setText }
    • Memory Management
      • Reuse cells no longer req'd to generate current display instance of allocation across all table cells
  • Navigation Controller { allow user to drill down multiple views of data }
  • Navigation Controller Stack { new views appear when view controllers are instantiated and pushed onto the navigation controller stack or to go back the navigation controller pops the current view off the stack to unload it and previous view moves to top of stack and becomes active }
  • Apple Navigation-Base Application Template
    • Preparation
      • UINavigationController { instance of Root View Controller and subclass of UITableViewController. It is a navigation controller that provides functionality to push and pop other controllers }
        • Properties: { title property }
      • UINavigationBar { horizontal navigation bar with UI elements to navigate views }
      • UINavigationItem { used to display title in navigation bar }
Links:

Friday, 25 April 2014

Post WDI - iPhone Multiview App Architecture (Multiple-View Controllers, Toolbars)

iPhone Development (Xcode 5) (Cont'd)

iPhone Multiview Apps (with Toolbar) (manually created)   DONE
  • UIViewController { load and swap multiple @class subviews (separate controller structure) with UIView instance method insertSubView:atIndex. use default controller to clear current view (i.e. clearView ), remove inactive subviews  where superview property is tested to be nil using removeFromSuperView for individual or simultaneous views }
  • UIToolbar and UIBarButtonItem { overlayed floating subview index to switch views based on event action (i.e. Touch Up Inside) }


iPhone Multiview Apps (with Tab Bar) (expedited method)   DONE
  • UITabBar and UITabBarController (not the Apple default tab bar)
    • UITabBarControllerDelegate Protocol has all optional methods 
    • appplicationDidFinishLaunching method to add tabBarViewController instance
    • floatValue of NSString class provides floating point numbers from user input returning 0.0 for incorrect input allowing valid calculation always
    • viewWillAppear method used as hook to only update view just before displayed onscreen when we have access to all objects

Events Upcoming
    • ATTENDED - MyBirthdayApp, 28th Apr 2014
    • ATTENDED - Sydney MongoDB Meetup, 6pm, 29 Apr 2014 (MongoDB Australia, 2-12 Foveaux St Surry Hills)
    • ATTENDED - Entrepreneurs of 2025 - (Start Presenting To Groups) - 6:30pm 30 Apr 2014 (Level 1 99 York St) - Organiser and Host (Cyril Sansano) Beware: Nobody turned up except for me despite 11ppl RSVP'ing!!!
    • ATTENDED  - GA Launch Party - 6-9pm, Fri 2 May 2014 GA Sydney (York St), 56-58 York St

Post WDI - iPhone Interface Notifications, Alerts, AudioToolbox Framework (Modals, Action Sheets, Sounds, Vibrations)


iPhone Development (Xcode 5)
 (Cont'd)

iPhone / Cocoa Touch Interface Notifications and Alerts (   DONE
  • UIAlertView { modal alert window of message and options including 'delegate' actions upon dialog dismissal (i.e. low memory, dropped network, activity completion) }
    • Multi-Option Alerts 
      • otherButtonTitles for multiple buttons
      • UIAlertViewDelegate Protocol conformance (declared in header and 'delegate' pointer to object instantiating alert for effects after dismissal) and either alertView:clickedButtonAtIndex method for index of button pressed or buttonTitleAtIndex method to return its title (where not nil)
      • Constants { for defining button labels }
  • UIActionSheet { prompt decision from user based on actions (i.e. share, upload, bookmark, data modifications) }
    • Animated Opening from current View Controller UI Element { i.e. [actionSheet showInView:self.view]; } or Toolbar { showFromToolBar } or TabBar { showFromTabBar }
    • Custom Appearance { actionSheetStyle property (i.e. actionSheet.actionSheetStyle=UIBarStyleBlackTranslucent), or UIActionSheetStyleAutomatic (inherit any set view style), or UIActionSheetStyleBlackOpaque (shiny black) }
    • UIActionSheetDelegate Protocol conformance (declared in header and 'delegate' pointer to object instantiating action sheet for effects after dismissal) and either actionSheet:clickedButtonAtIndex method to capture index of button press event or buttonTitleAtIndex method to return its title (where not nil)
    • Dynamic Buttons { addButtonWithTitle method to add outside the 'initialization convenience method', in combination with cancelButtonIndex and destructiveButtonIndex }
  • System Sound Services API
    • Uses: potentially uninterruptive Sound, Alert, Vibrate notifications as user feedback, attention, error, action status
    • AudioToolbox Framework { add using menus and then import interface file with #import <AudioToolbox/AudioToolbox.h> }
    • Vibrations { substitute into stub method block kSystemSoundID_Vibrate }
  • Stub Methods { i.e. -(IBAction)doAction }