Showing posts with label responsive. Show all posts
Showing posts with label responsive. Show all posts

Saturday, 3 May 2014

Post WDI - iOS Development App (Master-Detail Table View, JSON, API, Mutable, Memory Management)

Activities @ TeamTreeHouse - 

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

DONE Building API Reader (Table View) iPhone App
  • Table View (List) with Master-Detail App
    • Manual
    • Master-Detail Template
  • UIApplication { single instance, only allowed one UIApplication object for a single app. watches for Events and Routes to appropriate targets }
  • AppDelegate
    • Dfn: capability to Intercept Events at an App level so can Add Custom code. all apps have it to hook into UIApplication (app lifecycle). responsible to ensure app has a Window 
    • .h { defines lifecycle of app }
    • .m { implementation of .h containing methods }
  • UIWindow object { coordinates presentation of Views on screen. hosting Views and working with UIApplication object to deliver Events to Views and View Controller }
  • View Controller object { manages presentation of app Content on screen, including Single MainView (property) and its Collection of Sub Views  i.e. self.view (where View is property of ViewController) }
  • UIViewController class { base class for all ViewController objects, provides Default functionality for Views' ability to load, display, respond, etc }
  • View object { draws Content in designated Rect area and Responds to Events in that area }
  • Controls { specialised Views responsible for implementing interface objects (i.e. buttons, text fields, toggle switches) }
  • Data { ways to store data in app (i.e. Core Data, etc) }
  • Storyboard (defines flow between ViewControllers)
    • MasterViewController { inherits from UITableViewController and UIViewController as displays List of TableView UITableView with Rows(UITableViewCells) attributes and behaviour and where tap event shows DetailViewController }
    • DetailViewController  { inherits from UIViewController as displays Single View Text from Table View Cell }
    • Scene { ViewControllers }
    • Segue {  connection between Scenes of type UIStoryboardSegue (arrow Transition between each View Controller). it has Properties: identifier, sourceViewController, destinationViewController }
      • identifier { read-only shown in View. accessed in code with method prepareForSegue. use Method notation (instead of Dot Notation) when dealing with 'read-only' info as indicated in Help }
      • prepareForSegue { intercepts Segue once it is triggered and takes two args }
        • Segue param { contains info about Segue }
        • sender { originator of Segue }
(UIStoryboardSegue *)segue sender:(id)sender
  • Shortcuts
    • Double-Click - Zoom in/out of Storyboard canvas 
    • CMD+N - New File
  • UITableViewController { is declared in NSObjCRuntime.h (according to hover+CMD+Click) and implements two Protocols. It contains a @property 'tableView' of type UITableView which implements the two Protocols }
    • UITableViewDataSource { defines what is displayed in Table View. it mediates between Table View and Data }
    • UITableViewDelegate { defines how Data displayed with Methods to configure Table Views (i.e. row heights, section headers/footers, tap event or editing actions) }
@property (nonatomic, retain) UITableView *tableView;

  • indexPath { object with two Properties (Section, and Row in that Section) }
  • Memory Management
    • No Table View Cell Reuse { alloc and init new table view cell for each row to be displayed in table view. slow with large quantities of rows in the array to be alloc'ed }
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    • Efficient Reuse of Table View Cells { allows table view to efficiently manage cells with each one having an identifier in storyboard so when table view cell scrolls beyond screen the table view re-marks it for reuse and recycles it on new row }
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

  • NSDictionary 
    • objectForKey { type 'id' is generic data type (any Object) }
    • valueForKey { always expects String }
// declaration for key value pair NSDictionary *blogPost1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"Blogpost1", @"title", @"Luke Schoen", @"author", nil]; 
// ALTERNATIVE convenience constructor for NSDictionary NSDictionary *blogPost1 = [NSDictionary dictionaryWithObjectsAndKeys:@"Blogpost1", @"title",@"Luke Schoen", @"author", nil];



  • SubTitles { Storyboard > Change Type (of TableViewCell) in Attribute Inspector > subTitle }
  • UITableViewCell Properties:
    • textLabel
    • detailTextLabel
  • Mutable 
    • Memory Inefficency { performance overhead when want to modify Contents of object, mem alloc needs to change and find mem space for additional Content }
    • NSMutableArray (subclass of NSArray)
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:0]; // if capacity 0, use below NSMutableArray *titles = [NSMutableArray array]; // memory alloc minimal to hold pointer to array [titles addObject:@“My Book”]; // add object to array. mem dynamically alloc. array size grows [titles insertObject:@“abc” atIndex:0];  [titles removeLastObject]; [titles removeObjectAtIndex:0]; 
    • NSMutableDictionary (subclass of NSDictionary)
      • Declare with Memory Capacity
NSMutableDictionary *book = [NSMutableDictionary dictionary]; [book setObject:@“My Book”, forKey:@”title”]; [book setObject:@“Luke Schoen”, forKey:@”author"]; [book removeObjectForKey:@“title”]; [book removeAllObjects]; // removes all objects from a dictionary
    • NSMutableString (subclass of NSString) 
NSMutableString *string = [NSMutableString string];[string appendString:@"Title: My Book"];[string appendString:@"Author: Luke Schoen"];[string insertString:@" -- " atIndex:10]; 
  • Immutable { cannot be modified } 
    • Memory Efficient { when variable for object alloc, mem req'd known (knows qty objects and kind of objects. pass around without need to modify }
    • NSArray
  • JSON Parsing (JavaScript Object Notation)
// create NSURL class object (convenience class to breakdown url) 
// download the data (NSData object stream from JSON)   
NSURL *movieURL = [NSURL URLWithString:@"http://www.omdbapi.com/?s=Terminator"]; 
// parse data  
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL]; 
// declare pointer in memory 
NSError *error = nil; 
// deserialise data into JSON object format to stored in dictionary 
// pass pointer reference to NSError so value can be modified by the method it is being passed to (otherwise just passing by value and can only read 
// i.e. &__ means value can be modified by the method 
// i.e. ___ means just passing its value and it can only read your object NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@", dataDictionary);
self.
moviePosts = [dataDictionary objectForKey:@"Search”];

// extract 'title' from NSDictionary and set
cell.textLabel.text = [moviePost valueForKey:@"Title"];
cell.detailTextLabel.text = [
moviePost valueForKey:@"Year"];


Events Upcoming
    • ATTENDED - RORO Syd Dev Hub - 6:30pm 6th May 2014 (Level 15, 2 Market St)
    • UNABLE - RORO USer Group - 7pm 13th May 2014 (Trinity Bar, 505 Crown St Surry Hills)
    • UNABLE - Sydney Drupal Meetup - 7pm, 15th May 2014 (Level 5, 48 Pirrama Rd)

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)