SlideShare une entreprise Scribd logo
1  sur  47
Getting Started
      Day 2
Where we’re headed
‣ Warmup and Review
‣ NSString, NSNumber, NSDate
‣ Collection Classes
‣ Classes & Objects Part 2
‣ Protocols and Categories
‣ CoreFoundation - NSUserDefaults
‣ Modifications to Fraction Calculator
‣ Simple Contact List
Simple Contact List
‣ Work with NSArrays
  and Dictionaries

‣ Inheritance and
  Introspection

‣ Delegate design patterns
‣ Storage with
  NSUserDefaults
Warmup and Review
Person Class
‣ Create a new project with a new class called
    “Person”
‣   Properties
    ‣   firstName
    ‣   lastName
    ‣   address
    ‣   city
    ‣   state
    ‣   emailAddress
    ‣   phoneNumber
‣ Override the -(NSString *)description method
‣ Create an initializer taking first and last name
‣ Create some of each type and print to console
Strings, Numbers, &
       Dates
NSString
‣   Represents an array of characters
‣   All strings are UTF-8
‣   No need to worry about null terminator
‣   Strings are immutable
‣   The @”” syntax creates a new string literal.
‣   Use NSMutableString for strings that will be
    modified
‣   Facilities for searching and comparing
NSNumber
‣ Storage class for numeric values
  ‣ chars, ints, floats, doubles, BOOL
  ‣ NSNumber will remember the type that was
       put into it.
‣   Use this class for storing numerics in collections
    (as we’ll see later)
‣   You can use NSDecimalNumber for a convenient
    wrapper for dealing with base 10 decimal numbers
NSDate
‣ Houses a single point in time.
‣ Has facilities for comparisons and date arithmetic
‣ Use NSDateFormatter to customize the printing
  of a given date
 NSDate *date = [[NSDate alloc] init];
 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"HH:mm 'on' EEEE MMMM d"];
 NSLog("%@", [formatter stringFromDate:date]);



‣ Format strings are based on the unicode standard.
Exercises
‣ Open the fraction calculator application from
    yesterday
    ‣ Modify the fraction class, adding an “asNumber”
      method to return the value of the fraction as an
      NSNumber.
‣   Modify the person class, adding a Date of Birth
    field.
    ‣ Add the appropriate property declaration
    ‣ BONUS: Create a method that returns the
      person’s age in years as an Integer.
    ‣ (Hint you will need use NSCalendar)
Collections
Collections Overview
‣   Provide common data structures
‣   Mutable and immutable flavors
‣   Collections work on objects only (ids).
‣   Primitives must stored converted to NSNumber
    or NSValue.
‣   Common types
    ‣ NSArray - contiguous, indexed memory
    ‣ NSDictionary - objects are accessed by a string
      key (aka Hashtable)
    ‣ NSSet - a bag of objects, unindexed. No
      duplicates.
NSArray
‣ Ordered collection of objects
‣ Access is constant time
‣ A valid index of an array cannot be nil. You can
    insert NSNull instead.
‣   Facilities for traversal, sorting, and querying.
‣   Arrays retain their members (more on this later)
Filtering / NSPredicate
‣ Filtering an array is simple using an NSPredicate:
 NSPredicate *predicate =
 [NSPredicate predicateWithFormat:@"lastName like %@", @"zearfoss"];


‣ Operation modifiers : [cd]
  ‣ “Case and diacritic insensitive”
  ‣ Diacritics means OHare == O’Hare
‣ Many operators available:
  ‣ Predicate Programming Guide
 NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
Sorting an Array
‣ Using NSSortDescriptor
  ‣ A sort descriptor contains a key and an ordering
      (ASC / DESC) :
 NSSortDescriptor *d
 
 = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
 NSArray *sds = [NSArray arrayWithObject:d];
 NSArray *sorted = [array sortedArrayUsingDescriptors:sds];
NSDictionary
‣   Associations of keys and values
‣   Only one value per key
‣   Keys are determined by calling isEqual on the key
‣   Key can be any object
‣   Cannot insert nil for a key, use NSNull
‣   Includes facilities for traversing
‣   Dictionaries retain their members
NSSet
‣ A completely unordered collection of objects
‣ Operations are fast (constant time) but no control
    over which object you get.
‣   Multiple objects can be added using an
    NSCountedSet
Mutability
‣ Use modifiable collections by using the mutable
  variant:
  ‣ NSMutableArray
  ‣ NSMutableDictionary
  ‣ NSMutableSet
  ‣ NSMutableCountedSet
Fast Enumeration
‣ Objects support traversal in a for . . . in construct
  for (id obj in array)
  {
  
 /* statements */
  }


‣ If you know what type of objects are in the array,
   you can specify that type in the loop:
  for (NSString *str in array)
  {
  
 /* statements */
  }
Quick Exercise
‣ Modify the person class to contain a dictionary of
    phone numbers with the following keys:
    ‣ “Office”
    ‣ “Home”
    ‣ “Cell”
    ‣ Use extern variables for the keys
‣   Create a method, phoneNumberForKey:
    (NSString *)key to get phone numbers
‣   Create another method, setPhoneNumberForKey:
    (NSString *)key
‣   Remove the property for phone numbers
Classes and Objects
       Part 2
Inheritance in Obj-c
‣ We have already see inheritance:
    @interface Calculator : NSObject

‣ Methods can be overridden, such as (NSString
    *)description
‣   While you don’t have to, all your classes should
    inherit NSObject
‣   Benefits of NSObject
    ‣ Reflection & Introspection
    ‣ Dynamic method invocation
    ‣ Basic equality checking
    ‣ Memory management benefits
Overriding initializers
‣ From the fraction class:
 -   (id)initWithNumerator:(int)num denominator:(int)denom
 {
 
   if (self = [super init])
 
   {
 
   
     numerator = num;
 
   
     denominator = denom != 0 ? denom : 1;
 
   }
 
 
   return self;
 }
Managing Memory
‣ Reference count system
  ‣ alloc . . . init gives a reference count of 1
  ‣ copy gives a reference count of 1
  ‣ retain raises the reference count
  ‣ release drops the reference count
‣ When an object reference count reaches 0 and is
    no longer in scope, it’s dealloc method is called and
    the object is destroyed.
‣   The Rule: If you alloc, copy, or retain an object,
    you must release.
Examples
‣ This must be released (alloc . . . init)
  NSArray *array = [[NSArray alloc] init];


‣ This must be released (copied)
  NSArray *array2 = [array copy];


‣ This should not be released (no alloc, copy, retain)
  NSArray *array = [NSArray array];


‣ This must be released (reatined)
  NSArray *array = [[NSArray array] retain];
The Autorelease Pool
‣ Messages from convenience constructors should
  send objects an autorelease message.
  ‣ Objects sent an autorelease message are added
    to the autorelease pool.
  ‣ The pool is drained at the end of the event loop
    cycle, at which point all objects are sent a
    release message.
  ‣ You have no control over when autorelease
    pools are drained.
  ‣ Attempting to release an autoreleased object
    will raise an exception.
Fraction Calculator
‣ In main.m
 int main(int argc, char *argv[])
 {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
 }



‣ In fraction.m
 - (Fraction *)add:(Fraction *)fraction
 {
 
 ...
 
 Fraction *result = [[Fraction alloc] initWithNumerator:resultNum
                                  denominator:resultDenom];

 
   [result reduce];
 
 
   return [result autorelease];
 }
Why?
‣ Fraction : : add: does not contain the words copy
  or init

‣ The sender of the add message has no indication
  that it should assume memory management
  responsibility over the returned object.
Polymorphism and
Dynamic Binding
‣ Objects are dynamically typed at run-time
‣ Overridden methods are resolved by receiver
    type, not to pointer type.
‣   Analogous to virtual in C++
‣   Referred to as late binding
‣   (You always get what you expect)
Example
     @interface Base : NSObject
{
}

- (void)printMe;

@end

@interface Derived : Base
{
}

- (void)printMe;

@end

/* ... */

Base *obj = [[Derived alloc] init];
[obj printMe];
The Class Object
‣ Classes themselves are objects
‣ Calling a class (static) method calls a method on
  the class object.

‣ Aids in introspection
‣ Get the class object by calling [anObject class]
Object Introspection
‣ Objects know what kind of class they are.
‣ These methods are built into the NSObject class
  (another reason to always subclass NSObject).
                              True if the receiver is or
isKindOfClass:(Class)
                               inherits from the class
                              True if the receiver is an
isMemberOfClass:(Class)
                                instance of the class
                              True if the receiver is or
isSubclassOfClass:(Class)
                               inherits from the class
                            True if the supplied selector
respondsToSelector:(SEL)
                                      is defined
All things are types
‣ Virtually all Objective-c constructs are types, and
    may be used as such:
    ‣   Classes (as we’ve seen)
    ‣   Methods (compile time methods)
    ‣   Selectors (run time methods)
    ‣   IVars
    ‣   Properties
    ‣   Categories (coming later)
    ‣   Protocols (coming later)
‣ Details about these are found in the Runtime
    Reference
‣   Classes and Selectors are commonly used.
Object Equality
 NSString *str = @"foo";
 NSArray *a1 = [NSArray arrayWithObject:str];
 NSArray *a2 = [NSArray arrayWithObject:str];

 NSLog(@"%d", (a1 == a2));
 // FALSE!!!



‣ Objects are pointers, therefore == compares
  addresses.

‣ Objects should override isEqual: where we want to
  be able to check for object equality.
Exercises
‣ Fraction class
  ‣ Create a convenience constructor for the
      fraction class:
      +(Fraction *)fractionWith . . . .
  ‣   Override isEqual:(id)
  ‣   Override -(id)copy
More Exercises
‣ Create 2 subclasses of Person
 ‣ Client with properties:
    companyName, companyPhone
 ‣ Employee with properties:
    departmentName, managerName, title
‣ Override initializers and create convenience
  constructors:
 ‣ personWithFirstName:LastName:
 ‣ clientWithFirstName:LastName:Company
 ‣ employeeWithFirstName:LastName:Department:
‣ Provide -(id)copy and isEqual for Person and
  derived classes.
Protocols & Categories
Protocols
‣ Analogous to Interfaces in Java, pure virtual in C++
‣ Defines a set of methods that an object may
    implement.
‣   Allows for anonymous objects
‣   Often used for delegate definitions, offloading
    some custom functionality to another class.
‣   Objects are said to “conform to a protocol”
‣   Formal protocols are named, informal protocols
    exist in the frameworks.
‣   Formal protocols can contain @required and
    @optional members
Example Protocols
                                  Defines methods for copying
 NSCopying
                                             of objects
                                  Defines methods for archival
 NSCoding
                                             of objects
                                  Provides additional base level
 NSObject
                                         object methods
                                    Defines some application
 UIApplicationDelegate
                                        lifecycle methods

‣ Adopting a protocol:
@interface MyClass : NSObject <NSCoding, NSCopying>
{
}
@end
Defining a Protocol
 @protocol myProtocol

 @optional
 - (void)optionalMethod:(int)arg;

 @required
 - (void)requiredMethod:(int)arg;

 @property (nonatomic, assign) int someProperty;

 @end


‣ Protocols may do anything but define iVars
‣ Protocols may also conform to other protocols
‣ Type for an object conforming to a protocol:
  ‣ id<Protocol> obj;
Categories
‣ No analog in any other language (that I know of)
‣ Allow for composite classes
‣ Allows the developer to add functionality to class
    without subclassing
‣   Categories can:
    ‣ Override existing methods
    ‣ Add methods to an existing class
    ‣ Adopt a protocol
‣   Categories cannot:
    ‣ Add iVars to a class
Using a Category
‣ Interface File:
  @interface NSString
 (VP)

  + (NSString*)stringWithUUID;

  @end


‣ Implementation
  @implementation NSValue(Selector)
  + (NSString*)stringWithUUID
  {
    // Create a new UUID
    CFUUIDRef uuidObj = CFUUIDCreate(nil);

      // Get the string representation of the UUID
      NSString *newUUID = (NSString*)CFUUIDCreateString(nil, uuidObj);
      CFRelease(uuidObj);
      return [newUUID autorelease];
  }
Exercises
‣ Modify the person and fraction classes to handle
  the following:
  ‣ NSCopying Protocol
  ‣ NSCoding Protocol
‣ Create a category on NSNumber to allow to for
  initialization with a fraction:
  ‣ +(NSNumber *)numberWithFraction:
     (Fraction*)
CoreFoundation:
NSUserDefaults
NSUserDefaults
‣ Designed for holding small bits of user preference
  data

‣ BUT, can be used for saving application state
  between sessions

 [[NSUserDefaults standardUserDefaults] setObject:anObject
 forKey:@"myObject"];



‣ (There are better ways of doing this, which we’ll
  cover tomorrow)
Simple Contact List
Simple Contact List
‣ Use project shell provided
‣ Use person, employee, and client classes
‣ Use introspection to show clients and employees
    differently
‣   Use filtering to allow the user to screen objects by
    name
‣   Use sorting to always sort the list by last name

Contenu connexe

Tendances

Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesCody Yun
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
GC in Smalltalk - Now What?
GC in Smalltalk - Now What?GC in Smalltalk - Now What?
GC in Smalltalk - Now What?ESUG
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWithTheBest
 
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...Paris Open Source Summit
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?Dina Goldshtein
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql M. S.
 

Tendances (20)

Java session 3
Java session 3Java session 3
Java session 3
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
GC in Smalltalk - Now What?
GC in Smalltalk - Now What?GC in Smalltalk - Now What?
GC in Smalltalk - Now What?
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...
#OSSPARIS19 : Detecter des anomalies de séries temporelles à la volée avec Wa...
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
 

En vedette

Frederick web meetup slides
Frederick web meetup slidesFrederick web meetup slides
Frederick web meetup slidesPat Zearfoss
 
Easy dna paternity testing
Easy dna paternity testingEasy dna paternity testing
Easy dna paternity testingJack Smith
 
Unit 6 Fourth Grade 2012 2013
Unit 6 Fourth Grade 2012 2013Unit 6 Fourth Grade 2012 2013
Unit 6 Fourth Grade 2012 2013Isaac_Schools_5
 
What Apple's iOS 5 Means for Marketers
What Apple's iOS 5 Means for MarketersWhat Apple's iOS 5 Means for Marketers
What Apple's iOS 5 Means for MarketersBen Gaddis
 

En vedette (7)

Frederick web meetup slides
Frederick web meetup slidesFrederick web meetup slides
Frederick web meetup slides
 
iOS 5
iOS 5iOS 5
iOS 5
 
Easy dna paternity testing
Easy dna paternity testingEasy dna paternity testing
Easy dna paternity testing
 
Fwt ios 5
Fwt ios 5Fwt ios 5
Fwt ios 5
 
Unit 6 Fourth Grade 2012 2013
Unit 6 Fourth Grade 2012 2013Unit 6 Fourth Grade 2012 2013
Unit 6 Fourth Grade 2012 2013
 
What Apple's iOS 5 Means for Marketers
What Apple's iOS 5 Means for MarketersWhat Apple's iOS 5 Means for Marketers
What Apple's iOS 5 Means for Marketers
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 

Similaire à Day 2

JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core DataMatthew Morey
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.pptshivani366010
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 

Similaire à Day 2 (20)

JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Scala idioms
Scala idiomsScala idioms
Scala idioms
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Slides
SlidesSlides
Slides
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 

Day 2

  • 2. Where we’re headed ‣ Warmup and Review ‣ NSString, NSNumber, NSDate ‣ Collection Classes ‣ Classes & Objects Part 2 ‣ Protocols and Categories ‣ CoreFoundation - NSUserDefaults ‣ Modifications to Fraction Calculator ‣ Simple Contact List
  • 3. Simple Contact List ‣ Work with NSArrays and Dictionaries ‣ Inheritance and Introspection ‣ Delegate design patterns ‣ Storage with NSUserDefaults
  • 5. Person Class ‣ Create a new project with a new class called “Person” ‣ Properties ‣ firstName ‣ lastName ‣ address ‣ city ‣ state ‣ emailAddress ‣ phoneNumber ‣ Override the -(NSString *)description method ‣ Create an initializer taking first and last name ‣ Create some of each type and print to console
  • 7. NSString ‣ Represents an array of characters ‣ All strings are UTF-8 ‣ No need to worry about null terminator ‣ Strings are immutable ‣ The @”” syntax creates a new string literal. ‣ Use NSMutableString for strings that will be modified ‣ Facilities for searching and comparing
  • 8. NSNumber ‣ Storage class for numeric values ‣ chars, ints, floats, doubles, BOOL ‣ NSNumber will remember the type that was put into it. ‣ Use this class for storing numerics in collections (as we’ll see later) ‣ You can use NSDecimalNumber for a convenient wrapper for dealing with base 10 decimal numbers
  • 9. NSDate ‣ Houses a single point in time. ‣ Has facilities for comparisons and date arithmetic ‣ Use NSDateFormatter to customize the printing of a given date NSDate *date = [[NSDate alloc] init]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"HH:mm 'on' EEEE MMMM d"]; NSLog("%@", [formatter stringFromDate:date]); ‣ Format strings are based on the unicode standard.
  • 10. Exercises ‣ Open the fraction calculator application from yesterday ‣ Modify the fraction class, adding an “asNumber” method to return the value of the fraction as an NSNumber. ‣ Modify the person class, adding a Date of Birth field. ‣ Add the appropriate property declaration ‣ BONUS: Create a method that returns the person’s age in years as an Integer. ‣ (Hint you will need use NSCalendar)
  • 12. Collections Overview ‣ Provide common data structures ‣ Mutable and immutable flavors ‣ Collections work on objects only (ids). ‣ Primitives must stored converted to NSNumber or NSValue. ‣ Common types ‣ NSArray - contiguous, indexed memory ‣ NSDictionary - objects are accessed by a string key (aka Hashtable) ‣ NSSet - a bag of objects, unindexed. No duplicates.
  • 13. NSArray ‣ Ordered collection of objects ‣ Access is constant time ‣ A valid index of an array cannot be nil. You can insert NSNull instead. ‣ Facilities for traversal, sorting, and querying. ‣ Arrays retain their members (more on this later)
  • 14. Filtering / NSPredicate ‣ Filtering an array is simple using an NSPredicate: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastName like %@", @"zearfoss"]; ‣ Operation modifiers : [cd] ‣ “Case and diacritic insensitive” ‣ Diacritics means OHare == O’Hare ‣ Many operators available: ‣ Predicate Programming Guide NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
  • 15. Sorting an Array ‣ Using NSSortDescriptor ‣ A sort descriptor contains a key and an ordering (ASC / DESC) : NSSortDescriptor *d = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]; NSArray *sds = [NSArray arrayWithObject:d]; NSArray *sorted = [array sortedArrayUsingDescriptors:sds];
  • 16. NSDictionary ‣ Associations of keys and values ‣ Only one value per key ‣ Keys are determined by calling isEqual on the key ‣ Key can be any object ‣ Cannot insert nil for a key, use NSNull ‣ Includes facilities for traversing ‣ Dictionaries retain their members
  • 17. NSSet ‣ A completely unordered collection of objects ‣ Operations are fast (constant time) but no control over which object you get. ‣ Multiple objects can be added using an NSCountedSet
  • 18. Mutability ‣ Use modifiable collections by using the mutable variant: ‣ NSMutableArray ‣ NSMutableDictionary ‣ NSMutableSet ‣ NSMutableCountedSet
  • 19. Fast Enumeration ‣ Objects support traversal in a for . . . in construct for (id obj in array) { /* statements */ } ‣ If you know what type of objects are in the array, you can specify that type in the loop: for (NSString *str in array) { /* statements */ }
  • 20. Quick Exercise ‣ Modify the person class to contain a dictionary of phone numbers with the following keys: ‣ “Office” ‣ “Home” ‣ “Cell” ‣ Use extern variables for the keys ‣ Create a method, phoneNumberForKey: (NSString *)key to get phone numbers ‣ Create another method, setPhoneNumberForKey: (NSString *)key ‣ Remove the property for phone numbers
  • 22. Inheritance in Obj-c ‣ We have already see inheritance: @interface Calculator : NSObject ‣ Methods can be overridden, such as (NSString *)description ‣ While you don’t have to, all your classes should inherit NSObject ‣ Benefits of NSObject ‣ Reflection & Introspection ‣ Dynamic method invocation ‣ Basic equality checking ‣ Memory management benefits
  • 23. Overriding initializers ‣ From the fraction class: - (id)initWithNumerator:(int)num denominator:(int)denom { if (self = [super init]) { numerator = num; denominator = denom != 0 ? denom : 1; } return self; }
  • 24. Managing Memory ‣ Reference count system ‣ alloc . . . init gives a reference count of 1 ‣ copy gives a reference count of 1 ‣ retain raises the reference count ‣ release drops the reference count ‣ When an object reference count reaches 0 and is no longer in scope, it’s dealloc method is called and the object is destroyed. ‣ The Rule: If you alloc, copy, or retain an object, you must release.
  • 25. Examples ‣ This must be released (alloc . . . init) NSArray *array = [[NSArray alloc] init]; ‣ This must be released (copied) NSArray *array2 = [array copy]; ‣ This should not be released (no alloc, copy, retain) NSArray *array = [NSArray array]; ‣ This must be released (reatined) NSArray *array = [[NSArray array] retain];
  • 26. The Autorelease Pool ‣ Messages from convenience constructors should send objects an autorelease message. ‣ Objects sent an autorelease message are added to the autorelease pool. ‣ The pool is drained at the end of the event loop cycle, at which point all objects are sent a release message. ‣ You have no control over when autorelease pools are drained. ‣ Attempting to release an autoreleased object will raise an exception.
  • 27. Fraction Calculator ‣ In main.m int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } ‣ In fraction.m - (Fraction *)add:(Fraction *)fraction { ... Fraction *result = [[Fraction alloc] initWithNumerator:resultNum denominator:resultDenom]; [result reduce]; return [result autorelease]; }
  • 28. Why? ‣ Fraction : : add: does not contain the words copy or init ‣ The sender of the add message has no indication that it should assume memory management responsibility over the returned object.
  • 29. Polymorphism and Dynamic Binding ‣ Objects are dynamically typed at run-time ‣ Overridden methods are resolved by receiver type, not to pointer type. ‣ Analogous to virtual in C++ ‣ Referred to as late binding ‣ (You always get what you expect)
  • 30. Example @interface Base : NSObject { } - (void)printMe; @end @interface Derived : Base { } - (void)printMe; @end /* ... */ Base *obj = [[Derived alloc] init]; [obj printMe];
  • 31. The Class Object ‣ Classes themselves are objects ‣ Calling a class (static) method calls a method on the class object. ‣ Aids in introspection ‣ Get the class object by calling [anObject class]
  • 32. Object Introspection ‣ Objects know what kind of class they are. ‣ These methods are built into the NSObject class (another reason to always subclass NSObject). True if the receiver is or isKindOfClass:(Class) inherits from the class True if the receiver is an isMemberOfClass:(Class) instance of the class True if the receiver is or isSubclassOfClass:(Class) inherits from the class True if the supplied selector respondsToSelector:(SEL) is defined
  • 33. All things are types ‣ Virtually all Objective-c constructs are types, and may be used as such: ‣ Classes (as we’ve seen) ‣ Methods (compile time methods) ‣ Selectors (run time methods) ‣ IVars ‣ Properties ‣ Categories (coming later) ‣ Protocols (coming later) ‣ Details about these are found in the Runtime Reference ‣ Classes and Selectors are commonly used.
  • 34. Object Equality NSString *str = @"foo"; NSArray *a1 = [NSArray arrayWithObject:str]; NSArray *a2 = [NSArray arrayWithObject:str]; NSLog(@"%d", (a1 == a2)); // FALSE!!! ‣ Objects are pointers, therefore == compares addresses. ‣ Objects should override isEqual: where we want to be able to check for object equality.
  • 35. Exercises ‣ Fraction class ‣ Create a convenience constructor for the fraction class: +(Fraction *)fractionWith . . . . ‣ Override isEqual:(id) ‣ Override -(id)copy
  • 36. More Exercises ‣ Create 2 subclasses of Person ‣ Client with properties: companyName, companyPhone ‣ Employee with properties: departmentName, managerName, title ‣ Override initializers and create convenience constructors: ‣ personWithFirstName:LastName: ‣ clientWithFirstName:LastName:Company ‣ employeeWithFirstName:LastName:Department: ‣ Provide -(id)copy and isEqual for Person and derived classes.
  • 38. Protocols ‣ Analogous to Interfaces in Java, pure virtual in C++ ‣ Defines a set of methods that an object may implement. ‣ Allows for anonymous objects ‣ Often used for delegate definitions, offloading some custom functionality to another class. ‣ Objects are said to “conform to a protocol” ‣ Formal protocols are named, informal protocols exist in the frameworks. ‣ Formal protocols can contain @required and @optional members
  • 39. Example Protocols Defines methods for copying NSCopying of objects Defines methods for archival NSCoding of objects Provides additional base level NSObject object methods Defines some application UIApplicationDelegate lifecycle methods ‣ Adopting a protocol: @interface MyClass : NSObject <NSCoding, NSCopying> { } @end
  • 40. Defining a Protocol @protocol myProtocol @optional - (void)optionalMethod:(int)arg; @required - (void)requiredMethod:(int)arg; @property (nonatomic, assign) int someProperty; @end ‣ Protocols may do anything but define iVars ‣ Protocols may also conform to other protocols ‣ Type for an object conforming to a protocol: ‣ id<Protocol> obj;
  • 41. Categories ‣ No analog in any other language (that I know of) ‣ Allow for composite classes ‣ Allows the developer to add functionality to class without subclassing ‣ Categories can: ‣ Override existing methods ‣ Add methods to an existing class ‣ Adopt a protocol ‣ Categories cannot: ‣ Add iVars to a class
  • 42. Using a Category ‣ Interface File: @interface NSString (VP) + (NSString*)stringWithUUID; @end ‣ Implementation @implementation NSValue(Selector) + (NSString*)stringWithUUID { // Create a new UUID CFUUIDRef uuidObj = CFUUIDCreate(nil); // Get the string representation of the UUID NSString *newUUID = (NSString*)CFUUIDCreateString(nil, uuidObj); CFRelease(uuidObj); return [newUUID autorelease]; }
  • 43. Exercises ‣ Modify the person and fraction classes to handle the following: ‣ NSCopying Protocol ‣ NSCoding Protocol ‣ Create a category on NSNumber to allow to for initialization with a fraction: ‣ +(NSNumber *)numberWithFraction: (Fraction*)
  • 45. NSUserDefaults ‣ Designed for holding small bits of user preference data ‣ BUT, can be used for saving application state between sessions [[NSUserDefaults standardUserDefaults] setObject:anObject forKey:@"myObject"]; ‣ (There are better ways of doing this, which we’ll cover tomorrow)
  • 47. Simple Contact List ‣ Use project shell provided ‣ Use person, employee, and client classes ‣ Use introspection to show clients and employees differently ‣ Use filtering to allow the user to screen objects by name ‣ Use sorting to always sort the list by last name

Notes de l'éditeur