Your SlideShare is downloading. ×
0
Getting Started
      Day 2
Where we’re headed
‣ Warmup and Review
‣ NSString, NSNumber, NSDate
‣ Collection Classes
‣ Classes & Objects Part 2
‣ Prot...
Simple Contact List
‣ Work with NSArrays
  and Dictionaries

‣ Inheritance and
  Introspection

‣ Delegate design patterns...
Warmup and Review
Person Class
‣ Create a new project with a new class called
    “Person”
‣   Properties
    ‣   firstName
    ‣   lastName
...
Strings, Numbers, &
       Dates
NSString
‣   Represents an array of characters
‣   All strings are UTF-8
‣   No need to worry about null terminator
‣   St...
NSNumber
‣ Storage class for numeric values
  ‣ chars, ints, floats, doubles, BOOL
  ‣ NSNumber will remember the type that...
NSDate
‣ Houses a single point in time.
‣ Has facilities for comparisons and date arithmetic
‣ Use NSDateFormatter to cust...
Exercises
‣ Open the fraction calculator application from
    yesterday
    ‣ Modify the fraction class, adding an “asNumb...
Collections
Collections Overview
‣   Provide common data structures
‣   Mutable and immutable flavors
‣   Collections work on objects o...
NSArray
‣ Ordered collection of objects
‣ Access is constant time
‣ A valid index of an array cannot be nil. You can
    i...
Filtering / NSPredicate
‣ Filtering an array is simple using an NSPredicate:
 NSPredicate *predicate =
 [NSPredicate predi...
Sorting an Array
‣ Using NSSortDescriptor
  ‣ A sort descriptor contains a key and an ordering
      (ASC / DESC) :
 NSSor...
NSDictionary
‣   Associations of keys and values
‣   Only one value per key
‣   Keys are determined by calling isEqual on ...
NSSet
‣ A completely unordered collection of objects
‣ Operations are fast (constant time) but no control
    over which o...
Mutability
‣ Use modifiable collections by using the mutable
  variant:
  ‣ NSMutableArray
  ‣ NSMutableDictionary
  ‣ NSMu...
Fast Enumeration
‣ Objects support traversal in a for . . . in construct
  for (id obj in array)
  {
  
 /* statements */
...
Quick Exercise
‣ Modify the person class to contain a dictionary of
    phone numbers with the following keys:
    ‣ “Offic...
Classes and Objects
       Part 2
Inheritance in Obj-c
‣ We have already see inheritance:
    @interface Calculator : NSObject

‣ Methods can be overridden,...
Overriding initializers
‣ From the fraction class:
 -   (id)initWithNumerator:(int)num denominator:(int)denom
 {
 
   if (...
Managing Memory
‣ Reference count system
  ‣ alloc . . . init gives a reference count of 1
  ‣ copy gives a reference coun...
Examples
‣ This must be released (alloc . . . init)
  NSArray *array = [[NSArray alloc] init];


‣ This must be released (...
The Autorelease Pool
‣ Messages from convenience constructors should
  send objects an autorelease message.
  ‣ Objects se...
Fraction Calculator
‣ In main.m
 int main(int argc, char *argv[])
 {
    NSAutoreleasePool * pool = [[NSAutoreleasePool al...
Why?
‣ Fraction : : add: does not contain the words copy
  or init

‣ The sender of the add message has no indication
  th...
Polymorphism and
Dynamic Binding
‣ Objects are dynamically typed at run-time
‣ Overridden methods are resolved by receiver...
Example
     @interface Base : NSObject
{
}

- (void)printMe;

@end

@interface Derived : Base
{
}

- (void)printMe;

@end...
The Class Object
‣ Classes themselves are objects
‣ Calling a class (static) method calls a method on
  the class object.
...
Object Introspection
‣ Objects know what kind of class they are.
‣ These methods are built into the NSObject class
  (anot...
All things are types
‣ Virtually all Objective-c constructs are types, and
    may be used as such:
    ‣   Classes (as we...
Object Equality
 NSString *str = @"foo";
 NSArray *a1 = [NSArray arrayWithObject:str];
 NSArray *a2 = [NSArray arrayWithOb...
Exercises
‣ Fraction class
  ‣ Create a convenience constructor for the
      fraction class:
      +(Fraction *)fractionW...
More Exercises
‣ Create 2 subclasses of Person
 ‣ Client with properties:
    companyName, companyPhone
 ‣ Employee with p...
Protocols & Categories
Protocols
‣ Analogous to Interfaces in Java, pure virtual in C++
‣ Defines a set of methods that an object may
    implemen...
Example Protocols
                                  Defines methods for copying
 NSCopying
                                ...
Defining a Protocol
 @protocol myProtocol

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

 @required
 - (void)requiredMethod...
Categories
‣ No analog in any other language (that I know of)
‣ Allow for composite classes
‣ Allows the developer to add ...
Using a Category
‣ Interface File:
  @interface NSString
 (VP)

  + (NSString*)stringWithUUID;

  @end


‣ Implementation
...
Exercises
‣ Modify the person and fraction classes to handle
  the following:
  ‣ NSCopying Protocol
  ‣ NSCoding Protocol...
CoreFoundation:
NSUserDefaults
NSUserDefaults
‣ Designed for holding small bits of user preference
  data

‣ BUT, can be used for saving application stat...
Simple Contact List
Simple Contact List
‣ Use project shell provided
‣ Use person, employee, and client classes
‣ Use introspection to show cl...
Upcoming SlideShare
Loading in...5
×

Day 2

1,490

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,490
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
39
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide






























































































  • Transcript of "Day 2"

    1. 1. Getting Started Day 2
    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. 3. Simple Contact List ‣ Work with NSArrays and Dictionaries ‣ Inheritance and Introspection ‣ Delegate design patterns ‣ Storage with NSUserDefaults
    4. 4. Warmup and Review
    5. 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
    6. 6. Strings, Numbers, & Dates
    7. 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. 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. 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. 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)
    11. 11. Collections
    12. 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. 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. 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. 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. 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. 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. 18. Mutability ‣ Use modifiable collections by using the mutable variant: ‣ NSMutableArray ‣ NSMutableDictionary ‣ NSMutableSet ‣ NSMutableCountedSet
    19. 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. 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
    21. 21. Classes and Objects Part 2
    22. 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. 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. 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. 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. 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. 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. 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. 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. 30. Example @interface Base : NSObject { } - (void)printMe; @end @interface Derived : Base { } - (void)printMe; @end /* ... */ Base *obj = [[Derived alloc] init]; [obj printMe];
    31. 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. 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. 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. 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. 35. Exercises ‣ Fraction class ‣ Create a convenience constructor for the fraction class: +(Fraction *)fractionWith . . . . ‣ Override isEqual:(id) ‣ Override -(id)copy
    36. 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.
    37. 37. Protocols & Categories
    38. 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. 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. 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. 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. 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. 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*)
    44. 44. CoreFoundation: NSUserDefaults
    45. 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)
    46. 46. Simple Contact List
    47. 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
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×