Palestra atheniense congresso cpc iamg uberaba

1.000 visualizações

Publicada em

palestra apresentada no evento do iamg em uberaba no dia 07/10/2010

Publicada em: Tecnologia
0 comentários
1 gostou
Estatísticas
Notas
  • Seja o primeiro a comentar

Sem downloads
Visualizações
Visualizações totais
1.000
No SlideShare
0
A partir de incorporações
0
Número de incorporações
2
Ações
Compartilhamentos
0
Downloads
4
Comentários
0
Gostaram
1
Incorporações 0
Nenhuma incorporação

Nenhuma nota no slide


















































































  • Palestra atheniense congresso cpc iamg uberaba

    1. 1. Getting Started Day 2 Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    3. 3. Simple Contact List ‣ Work with NSArrays and Dictionaries ‣ Inheritance and Introspection ‣ Delegate design patterns ‣ Storage with NSUserDefaults Thursday, October 7, 2010
    4. 4. Warmup and Review Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    6. 6. Strings, Numbers, & Dates Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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 to use NSCalendar) Thursday, October 7, 2010
    11. 11. Collections Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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) Thursday, October 7, 2010
    14. 14. Filtering / NSPredicate ‣ Filtering an array is simple using an NSPredicate: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.lastName like[cd] %@", @"z?"]; ‣ Operation modifiers : [cd] ‣ “Case and diacritic insensitive” ‣ Diacritics means OHare == O’Hare ‣ Many operators available: ‣ Predicate Programming Guide NSArray *filtered = [array filteredArrayUsingPredicate:predicate]; Thursday, October 7, 2010
    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]; Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    18. 18. Mutability ‣ Use modifiable collections by using the mutable variant: ‣ NSMutableArray ‣ NSMutableDictionary ‣ NSMutableSet ‣ NSMutableCountedSet Thursday, October 7, 2010
    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 */ } Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    21. 21. Classes and Objects Part 2 Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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; } Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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]; Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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]; } Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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) Thursday, October 7, 2010
    30. 30. Example @interface Base : NSObject { } - (void)printMe; @end @interface Derived : Base { } - (void)printMe; @end /* ... */ Base *obj = [[Derived alloc] init]; [obj printMe]; Thursday, October 7, 2010
    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] Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    35. 35. Exercises ‣ Fraction class ‣ Create a convenience constructor for the fraction class: +(Fraction *)fractionWith . . . . ‣ Override isEqual:(id) Thursday, October 7, 2010
    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. Thursday, October 7, 2010
    37. 37. Protocols & Categories Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    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; Thursday, October 7, 2010
    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 Thursday, October 7, 2010
    42. 42. Using a Category ‣ Interface File (NSString+UUID.h): @interface NSString (VP) + (NSString*)stringWithUUID; @end [NSString stringWithUUID]; ‣ Implementation (NSString+UUID.m): @implementation NSString(VP) + (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]; } Thursday, October 7, 2010
    43. 43. Exercises ‣ Modify the person class to handle the following: ‣ NSCopying Protocol ‣ NSCoding Protocol ‣ Create a category on NSNumber to allow to for initialization with a fraction: ‣ +(NSNumber *)numberWithFraction: (Fraction*) Thursday, October 7, 2010
    44. 44. CoreFoundation: NSUserDefaults Thursday, October 7, 2010
    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) Thursday, October 7, 2010
    46. 46. Simple Contact List Thursday, October 7, 2010
    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 Thursday, October 7, 2010

    ×