Showing posts with label pointers. Show all posts
Showing posts with label pointers. 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)

Monday, 21 April 2014

Post WDI - iOS Development, Objective-C (Object-Oriented), C-Programming (Procedural), XCode 5, Cocoa Touch

Activities @ TeamTreeHouse - 

iOS Development (using Xcode 5) with Douglass Turner - 
  • DONE Fundamentals of C (
    • Console Outputs
    • Code Source Files, 
    • Compiler (C Language), 
    • Executables, 
    • 'Include' Statement, 
    • Header Files prepended to Source Files before Build/Run and Conversion to Executable by Compiler, 
    • 'Main' Function entry point to C Programs,
    • Code Blocks and Statements, 
    • Return Types and Values for Functions, 
    • Variables {%d ints, %f floats, %c chars}, 
    • Array Declaration and Initialization, 
    • Operators {specify how variables manipulated}, 
    • Expressions {combine vars creating new values}, 
    • Auto Incrementing before/after Assignment, 
    • Modulus {Long Division Remainder})
  • DONE Functional Programming in C (
    • Control Flow Statements, 
      • For Loops, While and Do While Loops, 
      • If Else Conditional, 
      • Switch Statement Conditional {Comparisons}, 
    • Functions {Declaration, Main Function Use, Implementation}, 
    • Scoping Context Rules and Visibility
  • DONE Objective-C Basics (
    • Pointers to Memory Address, SizeOf, %ld, printf, 
      • Testing Length for Mem Usage Req'd in Bytes, 
      • Pointers '*xxx' Declaration {Tracks Values}, 
      • Pointer to Address '&xxx', 
      • Access/Retrieval De-Referencing Pointer '*xxx', 
      • Structs combined with Functions, 
      • Encapsulation {Well-defined fns with narrow focus to manage tedious programming aspects}) 
  • DONE Intro to Objective-C (
    • Compare Objective-C with Procedural C { 
      • Procedural-C All-in-one-file {typedef, fn, use in main, defined manipulation fns}
      • Objective-C {Object-Oriented Programming OOP} with Class-split-across-two-files {
      • .h header to manipulate class and @interfaces with others as base/super or subclass with instance methods  -(void), params and names associated with params and setters and getters, 
      • .m for background implementation not public}, 
    • C (Struct) VS OOP (Class/Objects)
    • Collections of Classes in Objective-C {NSArray, etc}, 
    • Calling Methods with [ ] {square brackets}, 
    • Allocating Memory {alloc} and Initializing {init}, 
    • @property {simplified setter and getter syntax with details covered by Compiler}, 
    • Inheritance where 'IS A' relationship exists {Base/Super Class with shared methods/properties and Sub Classes/Variations sharing characteristics, changeable in implementation of method or properties, same methods [aka messages] but diff results}, 
    • Composition where get another classes 'state'/'behaviour' / 'properties'/'methods' {want Capabilities of other Class without complexities/details which occurs in Inheritance where become like other Class, i.e. compose Shape with a Button where Button refers to/points to the Shape and gains its functionality}, 
    • Polymorphism 
  • Xcode 5 Shortcuts (CMD + [ --> Un-Indent Code, CMD + ] --> Indent Code)
  • DONE Cocoa Foundation Framework (
    • Objective-C Classes, 
    • Generality Theme of Object-Oriented Programming,
    • 'Init' special methods {i.e. initWithInt}, 
    • NSNumber Class, 
    • %@ to communicate with class to use its 'description' method to display info about it, 
    • Alloc Init (Convenience Constructors) VS
    • Literal Notation (simpler alternative to initialize), 
    • Concatenation {Nesting NSString Methods}, Uppercase, 
    • NSArray (retrieve only Container Class), 
    • NSMutableArray (modifiable generic wrapper Class), 
    • For 'In' Loop (construct 'in' creates local var to lookup array and auto increments code block), 
    • NSDictionary & NSMutableDictionary (collections of Key(unique)/Value pairs), Create using Preexisting Dictionaries) 
  • DONE Advanced Objective-C (
    • C Memory Mgmt {vars using Dynamic Memory} VS 
    • Objective-C Memory Mgmt {Compiler handled}, 
    • Memory Alloc & Free Calls {calls to free memory},
    • Reference Counting Technique of Objective-C {tracking qty of pointers referring to objects in app} Implem. by Compiler and Compiler Hints {from Developer}, 
    • Memory Deallocation when Reference Count is 'nil', 
    • Memory Mgmt Hints {provided via Properties to Compiler} @property(nonatomic{threading}, memory-directive) , 
    • Memory-Directors {Strong (i.e. parent), Copy (i.e. caters for mutable objects}, Weak (i.e. child), Assign}, Parent-Child Rel'ship (Strong/Weak References), 
    • 'Self' Keyword {refers to Object in context of specific instance of class where method being called}, 
    • 'Super' Keyword {calls implementation defined by Super Class and used to 'Override' their methods}, 
    • Categories {approach to create suites of methods sharing a common theme, it extends Classes by adding convenience methods to existing Classes that do not require Sub Classes to implement them}, 
    • Dynamic Typing {general purpose method capable of handling any type of object from any class using 'ID' data type as generic pointer, does not use * like normal types} 
    • Static Typing {when specifically declare type when create instance}, 
    • Objective-C Dynamic Language {flexibility as will always call the relevant Object on the fly}, 
    • 'Description' Method approach {so make obvious we're using it} NSLog(@"%@", [thing description]);
  • DONE Beyond the Basics 
    • Primitive Data (Scalar) Types { char %c, int %d, unsigned int %u,  long %ld, float %f, double %lf } (ordered by mem size req'd in bytes)
      • Fixed Mem Size (Compiler runtime auto allocates to mem block)
      • Auto Mem Addr Storage
    • Pointers
      • Dynamic Mem
      • Variable Storage
      • Mem Addr (i.e. printf("%p", &i);
      • "Passing by Value" (allocating mem twice for same data passed by reference is resource intensive)
      • Best Practice (Pointers)
        • Store Value Single Mem Location
        • Declare and Pass Pointers to Single Mem Location 
        • (i.e. int i = 100; int *i; i) i outputs mem address 
      • Arrays (Mem Addr points to first mem plus offset)
      • Alloc and Init (inherits from NSObject allowing Mem Mgmt)
        • (i.e. NSNumber *number = [[NSNumber alloc] initWithInt:100]
      • Literal Shorthand (Equivalents)
        • NSNumber *fortyTwo = @42; // performs alloc & init 
        • [NSNumber numberWithInt:42]
      • Compiler Directive (highlights shorthand notation in Objective-C, more readable and maintainable)
        • @ - Directive
        • @"" - NSString
        • @100 - NSNumber
        • @[ ] - NSArray
        • @ { } - NSDictionary
      • C Language Reference Documentation (highlights Equivalent Code Snippets)
      • @property - declaration sets up getters and setters methods
      • (nonatomic, ....) - not multi-threaded  (only one process of reading or writing and no decisions on prioritising access to data for multiple pointing processes
      • (...., strong) - reference for 'retaining' object/property with increasing retain count when property declared
      • (...., weak) - reference when no objection to underlying property being deallocated 
        • Parent Child relationship and referencing parent (self)
      • AFC (automatic reference counting) - previously versions req'd maintenance 
      • Retain Count - increase retain count by perform alloc and init causing an object to point to mem location. additional objects pointing to same mem address causes increase of retain count further (i.e. 2). assign pointer to nil for all pointers reduces retain count to 0 (no objects pointing to mem address) and can deallocate
        • NSLog(@“Retain count is %ld”, CFGetRetainCount((__bridge CFTypeRef)book1)); // where book1 is object retain count displaying
      • 'Retain' Cycle (i.e. Book *book1 = [[Book alloc] init]; book1.me = book1;) - creates retain cycle by 'me' child property of book1 (pointing to its parent). if execute (book1 = nil;) then 'me' property is still pointing to book1 so never releasing memory (Memory Leak caused)
      • Help - Document and API Reference
Activities - Other -


Curiosity