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
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.
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