SlideShare a Scribd company logo
1 of 76
Download to read offline
CS193P - Lecture 2
           iPhone Application Development

           Objective-C
           Foundation Framework




Thursday, January 7, 2010                   1
Announcements




Thursday, January 7, 2010   2
Announcements
        • Enrollment process is almost done




Thursday, January 7, 2010                     2
Announcements
        • Enrollment process is almost done




Thursday, January 7, 2010                     2
Announcements
        • Enrollment process is almost done

        • Shooting for end of day Friday




Thursday, January 7, 2010                     2
Announcements
        • Enrollment process is almost done

        • Shooting for end of day Friday

        • Please drop the class in Axess if you are not enrolled.




Thursday, January 7, 2010                                           2
Office Hours

        • David Jacobs
             ■   Mondays 4-6pm: Gates 360


        • Paul Salzman
             ■ Some time. Best to try all possible times until you hit it
             ■ Some place, probably in Gates. Just come by and yell real loud




Thursday, January 7, 2010                                                       3
iPhone SDK




Thursday, January 7, 2010   4
iPhone SDK




Thursday, January 7, 2010   4
iPhone SDK

        • Enrolled students will be invited to developer program
             ■ Login to Program Portal
             ■ Request a Certificate

             ■ Download and install the SDK




Thursday, January 7, 2010                                          4
iPhone SDK

        • Enrolled students will be invited to developer program
             ■ Login to Program Portal
             ■ Request a Certificate

             ■ Download and install the SDK




Thursday, January 7, 2010                                          4
iPhone SDK

        • Enrolled students will be invited to developer program
             ■ Login to Program Portal
             ■ Request a Certificate

             ■ Download and install the SDK




        • Will need your Device UDIDs - details to come




Thursday, January 7, 2010                                          4
iPhone SDK

        • Enrolled students will be invited to developer program
             ■ Login to Program Portal
             ■ Request a Certificate

             ■ Download and install the SDK




        • Will need your Device UDIDs - details to come




Thursday, January 7, 2010                                          4
iPhone SDK

        • Enrolled students will be invited to developer program
             ■ Login to Program Portal
             ■ Request a Certificate

             ■ Download and install the SDK




        • Will need your Device UDIDs - details to come

        • Auditors will need to sign up for Developer Program
          independently
             ■ Free for Simulator development
             ■ $99 for on-device development




Thursday, January 7, 2010                                          4
Getting Help
       • The assignment walks you
         through it
       • Key spots to look
            ■ API & Conceptual Docs in Xcode
            ■ Class header files

            ■ Docs, sample code, tech notes

              on Apple Developer Connection
              (ADC) site
                 ■   http://developer.apple.com
                 ■   Dev site uses Google search




Thursday, January 7, 2010                          5
Today’s Topics
        • Questions from Tuesday or Assignments?
        • Object Oriented Programming Overview
        • Objective-C Language
        • Common Foundation Classes




Thursday, January 7, 2010                          6
Object Basics




Thursday, January 7, 2010   7
OOP Vocabulary
        • Class: defines the grouping of data and code,
                 the “type” of an object
        • Instance: a specific allocation of a class
        • Method: a “function” that an object knows how to perform
        • Instance Variable (or “ivar”): a specific piece of data
                                         belonging to an object




Thursday, January 7, 2010                                            8
OOP Vocabulary
        • Encapsulation
             ■   keep implementation private and separate from interface
        • Polymorphism
             ■   different objects, same interface
        • Inheritance
             ■   hierarchical organization, share code, customize or extend
                 behaviors




Thursday, January 7, 2010                                                     9
Inheritance

             Superclass
                                       NSObject



                                       UIControl




              Subclass
                            UIButton               UITextField


        • Hierarchical relation between classes
        • Subclass “inherit” behavior and data from superclass
        • Subclasses can use, augment or replace superclass methods

Thursday, January 7, 2010                                             10
Inheritance

                                                                 Memory
             Superclass
                                       NSObject                  management




                                       UIControl




              Subclass
                            UIButton               UITextField


        • Hierarchical relation between classes
        • Subclass “inherit” behavior and data from superclass
        • Subclasses can use, augment or replace superclass methods

Thursday, January 7, 2010                                                     10
Inheritance

                                                                 Memory
             Superclass
                                       NSObject                  management



                                                                 Generic
                                       UIControl                 behaviors




              Subclass
                            UIButton               UITextField


        • Hierarchical relation between classes
        • Subclass “inherit” behavior and data from superclass
        • Subclasses can use, augment or replace superclass methods

Thursday, January 7, 2010                                                     10
Inheritance

                                                                 Memory
             Superclass
                                       NSObject                  management



                                                                 Generic
                                       UIControl                 behaviors



                                                                 Specific
              Subclass
                            UIButton               UITextField   behaviors


        • Hierarchical relation between classes
        • Subclass “inherit” behavior and data from superclass
        • Subclasses can use, augment or replace superclass methods

Thursday, January 7, 2010                                                     10
More OOP Info?
        • Drop by office hours to talk about basics of OOP
        • Tons of books and articles on OOP
        • Most Java or C++ book have OOP introductions
        • Objective-C 2.0 Programming Language
             ■   http://developer.apple.com/documentation/Cocoa/Conceptual/
                 ObjectiveC




Thursday, January 7, 2010                                                     11
Objective-C




Thursday, January 7, 2010   12
Objective-C
        • Strict superset of C
             ■ Mix C with ObjC
             ■ Or even C++ with ObjC (usually referred to as ObjC++)


        • A very simple language, but some new syntax
        • Single inheritance, classes inherit from one and only one
          superclass
        • Protocols define behavior that cross classes
        • Dynamic runtime
        • Loosely typed, if you’d like




Thursday, January 7, 2010                                              13
Syntax Additions
        • Small number of additions
        • Some new types
             ■ Anonymous object
             ■ Class

             ■ Selectors


        • Syntax for defining classes
        • Syntax for message expressions




Thursday, January 7, 2010                  14
Dynamic Runtime
        • Object creation
             ■ All objects allocated out of the heap
             ■ No stack based objects


        • Message dispatch
        • Introspection




Thursday, January 7, 2010                              15
OOP with ObjC




Thursday, January 7, 2010   16
Classes and Instances
        • In Objective-C, classes and instances are both objects
        • Class is the blueprint to create instances




Thursday, January 7, 2010                                          17
Classes and Instances
        • In Objective-C, classes and instances are both objects
        • Class is the blueprint to create instances

                                                        method
                      Class




                                                                      method
                                               method
                                                                 method
                                                        Data




                                                                                    method
                                                        method
                                                                           method
                             method                          Data
                                                        method




                                                                                                  method
                                                                 method
                                                                                         method
                                      method
                    method




                                                                      Data
                                                                 method
                             Data




                                                                                                           method
                                                                               method
                                                                                                       method
                                                                                Data
                                                                           method
                             method




                                                                                                                    method
                                                                                             method
                                                                                              Data
                                                                                         method

                                                                                                       method




Thursday, January 7, 2010                                                                                                    17
Classes and Objects
        • Classes declare state and behavior
        • State (data) is maintained using instance variables
        • Behavior is implemented using methods
        • Instance variables typically hidden
             ■   Accessible only using getter/setter methods




Thursday, January 7, 2010                                       18
OOP From ObjC Perspective
        • Everybody has their own spin on OOP
             ■   Apple is no different
        • For the spin on OOP from an ObjC perspective:
             ■ Read the “Object-Oriented Programming with Objective-C”
               document
             ■ http://developer.apple.com/iphone/library/documentation/

               Cocoa/Conceptual/OOP_ObjC




Thursday, January 7, 2010                                                 19
Messaging syntax




Thursday, January 7, 2010   20
Class and Instance Methods
        • Instances respond to instance methods
          - (id)init;
          - (float)height;
          - (void)walk;

        • Classes respond to class methods
          + (id)alloc;
          + (id)person;
          + (Person *)sharedPerson;




Thursday, January 7, 2010                         21
Message syntax




Thursday, January 7, 2010   22
Message syntax
         [receiver message]




Thursday, January 7, 2010     22
Message syntax
         [receiver message]

         [receiver message:argument]




Thursday, January 7, 2010              22
Message syntax
         [receiver message]

         [receiver message:argument]

         [receiver message:arg1 andArg:arg2]




Thursday, January 7, 2010                      22
Message examples
         Person *voter; //assume this exists

         [voter castBallot];

         int theAge = [voter age];

         [voter setAge:21];

         if ([voter canLegallyVote]) {
            // do something voter-y
         }

         [voter registerForState:@"CA" party:@"Independant"];

         NSString *name = [[voter spouse] name];




Thursday, January 7, 2010                                       23
Method definition examples
         Person *voter; //assume this exists
         - (void)castBallot;
         [voter castBallot];
         - (int)age;
         int theAge = [voter age];
         - (void)setAge:(int)age;
         [voter setAge:21];
         - (BOOL)canLegallyVote;
         if ([voter canLegallyVote]) {
            // do something voter-y
         }
         - (void)registerForState:(NSString*)state
                             party:(NSString*)party;
         [voter registerForState:@"CA" party:@"Independant"];
         - (Person*)spouse;
         - (NSString*)name;
         NSString *name = [[voter spouse] name];

Thursday, January 7, 2010                                       24
Terminology
        • Message expression
                   [receiver method: argument]

        • Message
                   [receiver method: argument]

        • Selector
                   [receiver method: argument]

        • Method
                   The code selected by a message




Thursday, January 7, 2010                           25
Dot Syntax
        • Objective-C 2.0 introduced dot syntax
        • Convenient shorthand for invoking accessor methods
          	 	 float height = [person height];
          	 	 float height = person.height;

          	 	 [person setHeight:newHeight];
          	 	 person.height = newHeight;


        • Follows the dots...
          	 	 [[person child] setHeight:newHeight];
          	 	 // exactly the same as
          	 	 person.child.height = newHeight;




Thursday, January 7, 2010                                      26
Objective-C Types




Thursday, January 7, 2010   27
Dynamic and static typing
       • Dynamically-typed object
         ! id anObject
             ■ Just id
             ■ Not id * (unless you really, really mean it...)


       • Statically-typed object
         ! Person *anObject

       • Objective-C provides compile-time, not runtime, type checking
       • Objective-C always uses dynamic binding




Thursday, January 7, 2010                                                28
The null object pointer
       • Test for nil explicitly
         ! if (person == nil) return;
       • Or implicitly
         ! if (!person) return;
       • Can use in assignments and as arguments if expected
         ! person = nil;
         ! [button setTarget: nil];
       • Sending a message to nil?
         ! person = nil;
         ! [person castBallot];


Thursday, January 7, 2010                                      29
BOOL typedef
       • When ObjC was developed, C had no boolean type (C99
         introduced one)
       • ObjC uses a typedef to define BOOL as a type
               BOOL flag = NO;
       • Macros included for initialization and comparison: YES and NO
               if (flag == YES)
               if (flag)
               if (!flag)
               if (flag != YES)
               flag = YES;
               flag = 1;

Thursday, January 7, 2010                                                30
Selectors identify methods by name
       • A selector has type SEL
         ! SEL action = [button action];
         ! [button setAction:@selector(start:)];

       • Conceptually similar to function pointer

       • Selectors include the name and all colons, for example:
         ! -(void)setName:(NSString *)name age:(int)age;
          would have a selector:
         ! SEL sel = @selector(setName:age:);



Thursday, January 7, 2010                                          31
Working with selectors
       • You can determine if an object responds to a given selector
         ! id obj;
         ! SEL sel = @selector(start:);
         ! if ([obj respondsToSelector:sel]) {
            ! [obj performSelector:sel withObject:self]
         ! }
       • This sort of introspection and dynamic messaging underlies
         many Cocoa design patterns
         ! -(void)setTarget:(id)target;
         ! -(void)setAction:(SEL)action;




Thursday, January 7, 2010                                              32
Working with Classes




Thursday, January 7, 2010      33
Class Introspection
        • You can ask an object about its class
         ! Class myClass = [myObject class];
         ! NSLog(@"My class is %@", [myObject className]);
        • Testing for general class membership (subclasses included):
         ! if ([myObject isKindOfClass:[UIControl class]]) {
            ! // something
         ! }
        • Testing for specific class membership (subclasses excluded):
         ! if ([myObject isMemberOfClass:[NSString class]]) {
            ! // something string specific
         ! }




Thursday, January 7, 2010                                                34
Working with Objects




Thursday, January 7, 2010      35
Identity versus Equality
        • Identity—testing equality of the pointer values
               if (object1 == object2) {
                    NSLog(@"Same exact object instance");
               }
        • Equality—testing object attributes
               if ([object1 isEqual: object2]) {
                    NSLog(@"Logically equivalent, but may
                            be different object instances");
               }




Thursday, January 7, 2010                                      36
-description
        • NSObject implements -description
               - (NSString *)description;
        • Objects represented in format strings using %@
        • When an object appears in a format string, it is asked for its
          description
               [NSString stringWithFormat: @”The answer is: %@”, myObject];

        • You can log an object’s description with:
               NSLog([anObject description]);
        • Your custom subclasses can override description to return
          more specific information




Thursday, January 7, 2010                                                     37
Foundation Classes




Thursday, January 7, 2010    38
Foundation Framework
        • Value and collection classes
        • User defaults
        • Archiving
        • Notifications
        • Undo manager
        • Tasks, timers, threads
        • File system, pipes, I/O, bundles




Thursday, January 7, 2010                    39
NSObject
        • Root class
        • Implements many basics
             ■ Memory management
             ■ Introspection

             ■ Object equality




Thursday, January 7, 2010          40
NSString
        • General-purpose Unicode string support
             ■   Unicode is a coding system which represents all of the world’s
                 languages
        • Consistently used throughout Cocoa Touch instead of “char *”
        • Without doubt the most commonly used class
        • Easy to support any language in the world with Cocoa




Thursday, January 7, 2010                                                         41
String Constants
       • In C constant strings are
         ! ! ! “simple”
       • In ObjC, constant strings are
         !         @“just as simple”
       • Constant strings are NSString instances
               ! NSString *aString = @”Hello World!”;




Thursday, January 7, 2010                               42
Format Strings
        • Similar to printf, but with %@ added for objects
          	 NSString *aString = @”Johnny”;
          	 NSString *log = [NSString stringWithFormat: @”It’s ‘%@’”, aString];


          log would be set to It’s       ‘Johnny’

        • Also used for logging
          	 NSLog(@”I am a %@, I have %d items”, [array className], [array count]);


          would log something like:
                  I am a NSArray, I have 5 items




Thursday, January 7, 2010                                                             43
NSString
        • Often ask an existing string for a new string with modifications
              - (NSString *)stringByAppendingString:(NSString *)string;
              - (NSString *)stringByAppendingFormat:(NSString *)string;
              - (NSString *)stringByDeletingPathComponent;


        • Example:
              NSString *myString = @”Hello”;
              NSString *fullString;
              fullString = [myString stringByAppendingString:@” world!”];

              fullString would be set to Hello   world!




Thursday, January 7, 2010                                                    44
NSString
        • Common NSString methods
               - (BOOL)isEqualToString:(NSString *)string;
               - (BOOL)hasPrefix:(NSString *)string;
               - (int)intValue;
               - (double)doubleValue;

        • Example:
              NSString *myString = @”Hello”;
              NSString *otherString = @”449”;
              if ([myString hasPrefix:@”He”]) {
                        // will make it here
              }
              if ([otherString intValue] > 500) {
                        // won’t make it here
              }


Thursday, January 7, 2010                                    45
NSMutableString
        • NSMutableString subclasses NSString
        • Allows a string to be modified
        • Common NSMutableString methods
                   + (id)string;
                   - (void)appendString:(NSString *)string;
                   - (void)appendFormat:(NSString *)format, ...;


                   NSMutableString *newString = [NSMutableString string];
                   [newString appendString:@”Hi”];
                   [newString appendFormat:@”, my favorite number is: %d”,
                        [self favoriteNumber]];




Thursday, January 7, 2010                                                    46
Collections
        • Array - ordered collection of objects
        • Dictionary - collection of key-value pairs
        • Set - unordered collection of unique objects
        • Common enumeration mechanism
        • Immutable and mutable versions
             ■ Immutable collections can be shared without side effect
             ■ Prevents unexpected changes

             ■ Mutable objects typically carry a performance overhead




Thursday, January 7, 2010                                                47
NSArray
       • Common NSArray methods
         ! + arrayWithObjects:(id)firstObj, ...;      // nil terminated!!!
         ! - (unsigned)count;
         ! - (id)objectAtIndex:(unsigned)index;
         ! - (unsigned)indexOfObject:(id)object;

       • NSNotFound returned for index if not found
              NSArray *array = [NSArray arrayWithObjects:@”Red”, @”Blue”,
              @”Green”, nil];
              if ([array indexOfObject:@”Purple”] == NSNotFound) {
                        NSLog (@”No color purple”);
              }

       • Be careful of the nil termination!!!



Thursday, January 7, 2010                                                    48
NSMutableArray
        • NSMutableArray subclasses NSArray
        • So, everything in NSArray
        • Common NSMutableArray Methods
         + (NSMutableArray *)array;
         - (void)addObject:(id)object;
         - (void)removeObject:(id)object;
         - (void)removeAllObjects;
         - (void)insertObject:(id)object atIndex:(unsigned)index;


         NSMutableArray *array = [NSMutableArray array];
         [array addObject:@”Red”];
         [array addObject:@”Green”];
         [array addObject:@”Blue”];
         [array removeObjectAtIndex:1];


Thursday, January 7, 2010                                           49
NSDictionary
       • Common NSDictionary methods
         + dictionaryWithObjectsAndKeys: (id)firstObject, ...;
         - (unsigned)count;
         - (id)objectForKey:(id)key;

       • nil returned if no object found for given key
            NSDictionary *colors = [NSDictionary
                  dictionaryWithObjectsAndKeys:@”Red”, @”Color 1”,
                  @”Green”, @”Color 2”, @”Blue”, @”Color 3”, nil];
            NSString *firstColor = [colors objectForKey:@”Color 1”];


            if ([colors objectForKey:@”Color 8”]) {
                   // won’t make it here
            }




Thursday, January 7, 2010                                              50
NSMutableDictionary
       • NSMutableDictionary subclasses NSDictionary
       • Common NSMutableDictionary methods
            + (NSMutableDictionary *)dictionary;
            - (void)setObject:(id)object forKey:(id)key;
            - (void)removeObjectForKey:(id)key;
            - (void)removeAllObjects;


            NSMutableDictionary *colors = [NSMutableDictionary dictionary];


            [colors setObject:@”Orange” forKey:@”HighlightColor”];




Thursday, January 7, 2010                                                     51
NSSet
       • Unordered collection of objects
       • Common NSSet methods
         ! + setWithObjects:(id)firstObj, ...;   // nil terminated
         ! - (unsigned)count;
         ! - (BOOL)containsObject:(id)object;




Thursday, January 7, 2010                                            52
NSMutableSet
        • NSMutableSet subclasses NSSet
       • Common NSMutableSet methods
         ! + (NSMutableSet *)set;
         ! - (void)addObject:(id)object;
         ! - (void)removeObject:(id)object;
         ! - (void)removeAllObjects;
         ! - (void)intersectSet:(NSSet *)otherSet;
         ! - (void)minusSet:(NSSet *)otherSet;




Thursday, January 7, 2010                            53
Enumeration
        • Consistent way of enumerating over objects in collections
        • Use with NSArray, NSDictionary, NSSet, etc.
              NSArray *array = ... ; // assume an array of People objects

              // old school
              Person *person;
              int count = [array count];
              for (i = 0; i < count; i++) {
                  person = [array objectAtIndex:i];
                  NSLog([person description]);
              }

              // new school
              for (Person *person in array) {
                 NSLog([person description]);
              }



Thursday, January 7, 2010                                                   54
NSNumber
       • In Objective-C, you typically use standard C number types
       • NSNumber is used to wrap C number types as objects
       • Subclass of NSValue
       • No mutable equivalent!
       • Common NSNumber methods
            + (NSNumber *)numberWithInt:(int)value;
            + (NSNumber *)numberWithDouble:(double)value;
            - (int)intValue;
            - (double)doubleValue;




Thursday, January 7, 2010                                            55
Other Classes
        • NSData / NSMutableData
             ■   Arbitrary sets of bytes
        • NSDate / NSCalendarDate
             ■   Times and dates




Thursday, January 7, 2010                  56
Getting some objects
        • Until we talk about memory management:
             ■   Use class factory methods
                     ■ NSString’s +stringWithFormat:
                     ■ NSArray’s +array

                     ■ NSDictionary’s +dictionary

             ■   Or any method that returns an object except alloc/init or copy.




Thursday, January 7, 2010                                                          57
More ObjC Info?
        • http://developer.apple.com/documentation/Cocoa/
          Conceptual/ObjectiveC
        • Concepts in Objective C are applicable to any other OOP
          language




Thursday, January 7, 2010                                           58
Questions?




Thursday, January 7, 2010   59

More Related Content

Similar to 02 Objective C

Image Processing and Computer Vision in iPhone and iPad
Image Processing and Computer Vision in iPhone and iPadImage Processing and Computer Vision in iPhone and iPad
Image Processing and Computer Vision in iPhone and iPadOge Marques
 
I phone udvikling best brains
I phone udvikling best brainsI phone udvikling best brains
I phone udvikling best brainsOve larsen
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.WO Community
 
Infusion for the birds
Infusion for the birdsInfusion for the birds
Infusion for the birdscolinbdclark
 
Getting Started with Wonder
Getting Started with WonderGetting Started with Wonder
Getting Started with WonderWO Community
 
Intro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CIntro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CAndrew Rohn
 
Architecting Smarter Apps with Entity Framework
Architecting Smarter Apps with Entity FrameworkArchitecting Smarter Apps with Entity Framework
Architecting Smarter Apps with Entity FrameworkSaltmarch Media
 
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSFred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSAxway Appcelerator
 
[doc].doc
[doc].doc[doc].doc
[doc].docbutest
 
Nuxeo World Session: Mobile ECM Apps with Nuxeo EP
Nuxeo World Session: Mobile ECM Apps with Nuxeo EPNuxeo World Session: Mobile ECM Apps with Nuxeo EP
Nuxeo World Session: Mobile ECM Apps with Nuxeo EPNuxeo
 
Javascript framework and backbone
Javascript framework and backboneJavascript framework and backbone
Javascript framework and backboneDaniel Lv
 
The iOS technical interview: get your dream job as an iOS developer
The iOS technical interview: get your dream job as an iOS developerThe iOS technical interview: get your dream job as an iOS developer
The iOS technical interview: get your dream job as an iOS developerJuan C Catalan
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptGarrison Locke
 
jQuery Comes to XPages
jQuery Comes to XPagesjQuery Comes to XPages
jQuery Comes to XPagesTeamstudio
 

Similar to 02 Objective C (20)

Image Processing and Computer Vision in iPhone and iPad
Image Processing and Computer Vision in iPhone and iPadImage Processing and Computer Vision in iPhone and iPad
Image Processing and Computer Vision in iPhone and iPad
 
I phone udvikling best brains
I phone udvikling best brainsI phone udvikling best brains
I phone udvikling best brains
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 
Infusion for the birds
Infusion for the birdsInfusion for the birds
Infusion for the birds
 
Getting Started with Wonder
Getting Started with WonderGetting Started with Wonder
Getting Started with Wonder
 
Intro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CIntro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-C
 
Architecting Smarter Apps with Entity Framework
Architecting Smarter Apps with Entity FrameworkArchitecting Smarter Apps with Entity Framework
Architecting Smarter Apps with Entity Framework
 
Slideshare presentation
Slideshare presentationSlideshare presentation
Slideshare presentation
 
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOSFred Spencer & Blain Hamon: Advanced Titanium for iOS
Fred Spencer & Blain Hamon: Advanced Titanium for iOS
 
[doc].doc
[doc].doc[doc].doc
[doc].doc
 
Nuxeo World Session: Mobile ECM Apps with Nuxeo EP
Nuxeo World Session: Mobile ECM Apps with Nuxeo EPNuxeo World Session: Mobile ECM Apps with Nuxeo EP
Nuxeo World Session: Mobile ECM Apps with Nuxeo EP
 
Roadshow cb
Roadshow cbRoadshow cb
Roadshow cb
 
Javascript framework and backbone
Javascript framework and backboneJavascript framework and backbone
Javascript framework and backbone
 
2. intro to java
2. intro to java2. intro to java
2. intro to java
 
2. intro to java
2. intro to java2. intro to java
2. intro to java
 
The iOS technical interview: get your dream job as an iOS developer
The iOS technical interview: get your dream job as an iOS developerThe iOS technical interview: get your dream job as an iOS developer
The iOS technical interview: get your dream job as an iOS developer
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
jQuery Comes to XPages
jQuery Comes to XPagesjQuery Comes to XPages
jQuery Comes to XPages
 
Railsconf 2010
Railsconf 2010Railsconf 2010
Railsconf 2010
 
Tomas Grails
Tomas GrailsTomas Grails
Tomas Grails
 

More from Mahmoud

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهMahmoud
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident InvestigationMahmoud
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation SkillsMahmoud
 
Building Papers
Building PapersBuilding Papers
Building PapersMahmoud
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Mahmoud
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Mahmoud
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar Mahmoud
 

More from Mahmoud (20)

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident Investigation
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation Skills
 
Building Papers
Building PapersBuilding Papers
Building Papers
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar
 
Teams Ar
Teams ArTeams Ar
Teams Ar
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

02 Objective C

  • 1. CS193P - Lecture 2 iPhone Application Development Objective-C Foundation Framework Thursday, January 7, 2010 1
  • 3. Announcements • Enrollment process is almost done Thursday, January 7, 2010 2
  • 4. Announcements • Enrollment process is almost done Thursday, January 7, 2010 2
  • 5. Announcements • Enrollment process is almost done • Shooting for end of day Friday Thursday, January 7, 2010 2
  • 6. Announcements • Enrollment process is almost done • Shooting for end of day Friday • Please drop the class in Axess if you are not enrolled. Thursday, January 7, 2010 2
  • 7. Office Hours • David Jacobs ■ Mondays 4-6pm: Gates 360 • Paul Salzman ■ Some time. Best to try all possible times until you hit it ■ Some place, probably in Gates. Just come by and yell real loud Thursday, January 7, 2010 3
  • 10. iPhone SDK • Enrolled students will be invited to developer program ■ Login to Program Portal ■ Request a Certificate ■ Download and install the SDK Thursday, January 7, 2010 4
  • 11. iPhone SDK • Enrolled students will be invited to developer program ■ Login to Program Portal ■ Request a Certificate ■ Download and install the SDK Thursday, January 7, 2010 4
  • 12. iPhone SDK • Enrolled students will be invited to developer program ■ Login to Program Portal ■ Request a Certificate ■ Download and install the SDK • Will need your Device UDIDs - details to come Thursday, January 7, 2010 4
  • 13. iPhone SDK • Enrolled students will be invited to developer program ■ Login to Program Portal ■ Request a Certificate ■ Download and install the SDK • Will need your Device UDIDs - details to come Thursday, January 7, 2010 4
  • 14. iPhone SDK • Enrolled students will be invited to developer program ■ Login to Program Portal ■ Request a Certificate ■ Download and install the SDK • Will need your Device UDIDs - details to come • Auditors will need to sign up for Developer Program independently ■ Free for Simulator development ■ $99 for on-device development Thursday, January 7, 2010 4
  • 15. Getting Help • The assignment walks you through it • Key spots to look ■ API & Conceptual Docs in Xcode ■ Class header files ■ Docs, sample code, tech notes on Apple Developer Connection (ADC) site ■ http://developer.apple.com ■ Dev site uses Google search Thursday, January 7, 2010 5
  • 16. Today’s Topics • Questions from Tuesday or Assignments? • Object Oriented Programming Overview • Objective-C Language • Common Foundation Classes Thursday, January 7, 2010 6
  • 18. OOP Vocabulary • Class: defines the grouping of data and code, the “type” of an object • Instance: a specific allocation of a class • Method: a “function” that an object knows how to perform • Instance Variable (or “ivar”): a specific piece of data belonging to an object Thursday, January 7, 2010 8
  • 19. OOP Vocabulary • Encapsulation ■ keep implementation private and separate from interface • Polymorphism ■ different objects, same interface • Inheritance ■ hierarchical organization, share code, customize or extend behaviors Thursday, January 7, 2010 9
  • 20. Inheritance Superclass NSObject UIControl Subclass UIButton UITextField • Hierarchical relation between classes • Subclass “inherit” behavior and data from superclass • Subclasses can use, augment or replace superclass methods Thursday, January 7, 2010 10
  • 21. Inheritance Memory Superclass NSObject management UIControl Subclass UIButton UITextField • Hierarchical relation between classes • Subclass “inherit” behavior and data from superclass • Subclasses can use, augment or replace superclass methods Thursday, January 7, 2010 10
  • 22. Inheritance Memory Superclass NSObject management Generic UIControl behaviors Subclass UIButton UITextField • Hierarchical relation between classes • Subclass “inherit” behavior and data from superclass • Subclasses can use, augment or replace superclass methods Thursday, January 7, 2010 10
  • 23. Inheritance Memory Superclass NSObject management Generic UIControl behaviors Specific Subclass UIButton UITextField behaviors • Hierarchical relation between classes • Subclass “inherit” behavior and data from superclass • Subclasses can use, augment or replace superclass methods Thursday, January 7, 2010 10
  • 24. More OOP Info? • Drop by office hours to talk about basics of OOP • Tons of books and articles on OOP • Most Java or C++ book have OOP introductions • Objective-C 2.0 Programming Language ■ http://developer.apple.com/documentation/Cocoa/Conceptual/ ObjectiveC Thursday, January 7, 2010 11
  • 26. Objective-C • Strict superset of C ■ Mix C with ObjC ■ Or even C++ with ObjC (usually referred to as ObjC++) • A very simple language, but some new syntax • Single inheritance, classes inherit from one and only one superclass • Protocols define behavior that cross classes • Dynamic runtime • Loosely typed, if you’d like Thursday, January 7, 2010 13
  • 27. Syntax Additions • Small number of additions • Some new types ■ Anonymous object ■ Class ■ Selectors • Syntax for defining classes • Syntax for message expressions Thursday, January 7, 2010 14
  • 28. Dynamic Runtime • Object creation ■ All objects allocated out of the heap ■ No stack based objects • Message dispatch • Introspection Thursday, January 7, 2010 15
  • 29. OOP with ObjC Thursday, January 7, 2010 16
  • 30. Classes and Instances • In Objective-C, classes and instances are both objects • Class is the blueprint to create instances Thursday, January 7, 2010 17
  • 31. Classes and Instances • In Objective-C, classes and instances are both objects • Class is the blueprint to create instances method Class method method method Data method method method method Data method method method method method method Data method Data method method method Data method method method method Data method method Thursday, January 7, 2010 17
  • 32. Classes and Objects • Classes declare state and behavior • State (data) is maintained using instance variables • Behavior is implemented using methods • Instance variables typically hidden ■ Accessible only using getter/setter methods Thursday, January 7, 2010 18
  • 33. OOP From ObjC Perspective • Everybody has their own spin on OOP ■ Apple is no different • For the spin on OOP from an ObjC perspective: ■ Read the “Object-Oriented Programming with Objective-C” document ■ http://developer.apple.com/iphone/library/documentation/ Cocoa/Conceptual/OOP_ObjC Thursday, January 7, 2010 19
  • 35. Class and Instance Methods • Instances respond to instance methods - (id)init; - (float)height; - (void)walk; • Classes respond to class methods + (id)alloc; + (id)person; + (Person *)sharedPerson; Thursday, January 7, 2010 21
  • 37. Message syntax [receiver message] Thursday, January 7, 2010 22
  • 38. Message syntax [receiver message] [receiver message:argument] Thursday, January 7, 2010 22
  • 39. Message syntax [receiver message] [receiver message:argument] [receiver message:arg1 andArg:arg2] Thursday, January 7, 2010 22
  • 40. Message examples Person *voter; //assume this exists [voter castBallot]; int theAge = [voter age]; [voter setAge:21]; if ([voter canLegallyVote]) { // do something voter-y } [voter registerForState:@"CA" party:@"Independant"]; NSString *name = [[voter spouse] name]; Thursday, January 7, 2010 23
  • 41. Method definition examples Person *voter; //assume this exists - (void)castBallot; [voter castBallot]; - (int)age; int theAge = [voter age]; - (void)setAge:(int)age; [voter setAge:21]; - (BOOL)canLegallyVote; if ([voter canLegallyVote]) { // do something voter-y } - (void)registerForState:(NSString*)state party:(NSString*)party; [voter registerForState:@"CA" party:@"Independant"]; - (Person*)spouse; - (NSString*)name; NSString *name = [[voter spouse] name]; Thursday, January 7, 2010 24
  • 42. Terminology • Message expression [receiver method: argument] • Message [receiver method: argument] • Selector [receiver method: argument] • Method The code selected by a message Thursday, January 7, 2010 25
  • 43. Dot Syntax • Objective-C 2.0 introduced dot syntax • Convenient shorthand for invoking accessor methods float height = [person height]; float height = person.height; [person setHeight:newHeight]; person.height = newHeight; • Follows the dots... [[person child] setHeight:newHeight]; // exactly the same as person.child.height = newHeight; Thursday, January 7, 2010 26
  • 45. Dynamic and static typing • Dynamically-typed object ! id anObject ■ Just id ■ Not id * (unless you really, really mean it...) • Statically-typed object ! Person *anObject • Objective-C provides compile-time, not runtime, type checking • Objective-C always uses dynamic binding Thursday, January 7, 2010 28
  • 46. The null object pointer • Test for nil explicitly ! if (person == nil) return; • Or implicitly ! if (!person) return; • Can use in assignments and as arguments if expected ! person = nil; ! [button setTarget: nil]; • Sending a message to nil? ! person = nil; ! [person castBallot]; Thursday, January 7, 2010 29
  • 47. BOOL typedef • When ObjC was developed, C had no boolean type (C99 introduced one) • ObjC uses a typedef to define BOOL as a type BOOL flag = NO; • Macros included for initialization and comparison: YES and NO if (flag == YES) if (flag) if (!flag) if (flag != YES) flag = YES; flag = 1; Thursday, January 7, 2010 30
  • 48. Selectors identify methods by name • A selector has type SEL ! SEL action = [button action]; ! [button setAction:@selector(start:)]; • Conceptually similar to function pointer • Selectors include the name and all colons, for example: ! -(void)setName:(NSString *)name age:(int)age; would have a selector: ! SEL sel = @selector(setName:age:); Thursday, January 7, 2010 31
  • 49. Working with selectors • You can determine if an object responds to a given selector ! id obj; ! SEL sel = @selector(start:); ! if ([obj respondsToSelector:sel]) { ! [obj performSelector:sel withObject:self] ! } • This sort of introspection and dynamic messaging underlies many Cocoa design patterns ! -(void)setTarget:(id)target; ! -(void)setAction:(SEL)action; Thursday, January 7, 2010 32
  • 50. Working with Classes Thursday, January 7, 2010 33
  • 51. Class Introspection • You can ask an object about its class ! Class myClass = [myObject class]; ! NSLog(@"My class is %@", [myObject className]); • Testing for general class membership (subclasses included): ! if ([myObject isKindOfClass:[UIControl class]]) { ! // something ! } • Testing for specific class membership (subclasses excluded): ! if ([myObject isMemberOfClass:[NSString class]]) { ! // something string specific ! } Thursday, January 7, 2010 34
  • 52. Working with Objects Thursday, January 7, 2010 35
  • 53. Identity versus Equality • Identity—testing equality of the pointer values if (object1 == object2) { NSLog(@"Same exact object instance"); } • Equality—testing object attributes if ([object1 isEqual: object2]) { NSLog(@"Logically equivalent, but may be different object instances"); } Thursday, January 7, 2010 36
  • 54. -description • NSObject implements -description - (NSString *)description; • Objects represented in format strings using %@ • When an object appears in a format string, it is asked for its description [NSString stringWithFormat: @”The answer is: %@”, myObject]; • You can log an object’s description with: NSLog([anObject description]); • Your custom subclasses can override description to return more specific information Thursday, January 7, 2010 37
  • 56. Foundation Framework • Value and collection classes • User defaults • Archiving • Notifications • Undo manager • Tasks, timers, threads • File system, pipes, I/O, bundles Thursday, January 7, 2010 39
  • 57. NSObject • Root class • Implements many basics ■ Memory management ■ Introspection ■ Object equality Thursday, January 7, 2010 40
  • 58. NSString • General-purpose Unicode string support ■ Unicode is a coding system which represents all of the world’s languages • Consistently used throughout Cocoa Touch instead of “char *” • Without doubt the most commonly used class • Easy to support any language in the world with Cocoa Thursday, January 7, 2010 41
  • 59. String Constants • In C constant strings are ! ! ! “simple” • In ObjC, constant strings are ! @“just as simple” • Constant strings are NSString instances ! NSString *aString = @”Hello World!”; Thursday, January 7, 2010 42
  • 60. Format Strings • Similar to printf, but with %@ added for objects NSString *aString = @”Johnny”; NSString *log = [NSString stringWithFormat: @”It’s ‘%@’”, aString]; log would be set to It’s ‘Johnny’ • Also used for logging NSLog(@”I am a %@, I have %d items”, [array className], [array count]); would log something like: I am a NSArray, I have 5 items Thursday, January 7, 2010 43
  • 61. NSString • Often ask an existing string for a new string with modifications - (NSString *)stringByAppendingString:(NSString *)string; - (NSString *)stringByAppendingFormat:(NSString *)string; - (NSString *)stringByDeletingPathComponent; • Example: NSString *myString = @”Hello”; NSString *fullString; fullString = [myString stringByAppendingString:@” world!”]; fullString would be set to Hello world! Thursday, January 7, 2010 44
  • 62. NSString • Common NSString methods - (BOOL)isEqualToString:(NSString *)string; - (BOOL)hasPrefix:(NSString *)string; - (int)intValue; - (double)doubleValue; • Example: NSString *myString = @”Hello”; NSString *otherString = @”449”; if ([myString hasPrefix:@”He”]) { // will make it here } if ([otherString intValue] > 500) { // won’t make it here } Thursday, January 7, 2010 45
  • 63. NSMutableString • NSMutableString subclasses NSString • Allows a string to be modified • Common NSMutableString methods + (id)string; - (void)appendString:(NSString *)string; - (void)appendFormat:(NSString *)format, ...; NSMutableString *newString = [NSMutableString string]; [newString appendString:@”Hi”]; [newString appendFormat:@”, my favorite number is: %d”, [self favoriteNumber]]; Thursday, January 7, 2010 46
  • 64. Collections • Array - ordered collection of objects • Dictionary - collection of key-value pairs • Set - unordered collection of unique objects • Common enumeration mechanism • Immutable and mutable versions ■ Immutable collections can be shared without side effect ■ Prevents unexpected changes ■ Mutable objects typically carry a performance overhead Thursday, January 7, 2010 47
  • 65. NSArray • Common NSArray methods ! + arrayWithObjects:(id)firstObj, ...; // nil terminated!!! ! - (unsigned)count; ! - (id)objectAtIndex:(unsigned)index; ! - (unsigned)indexOfObject:(id)object; • NSNotFound returned for index if not found NSArray *array = [NSArray arrayWithObjects:@”Red”, @”Blue”, @”Green”, nil]; if ([array indexOfObject:@”Purple”] == NSNotFound) { NSLog (@”No color purple”); } • Be careful of the nil termination!!! Thursday, January 7, 2010 48
  • 66. NSMutableArray • NSMutableArray subclasses NSArray • So, everything in NSArray • Common NSMutableArray Methods + (NSMutableArray *)array; - (void)addObject:(id)object; - (void)removeObject:(id)object; - (void)removeAllObjects; - (void)insertObject:(id)object atIndex:(unsigned)index; NSMutableArray *array = [NSMutableArray array]; [array addObject:@”Red”]; [array addObject:@”Green”]; [array addObject:@”Blue”]; [array removeObjectAtIndex:1]; Thursday, January 7, 2010 49
  • 67. NSDictionary • Common NSDictionary methods + dictionaryWithObjectsAndKeys: (id)firstObject, ...; - (unsigned)count; - (id)objectForKey:(id)key; • nil returned if no object found for given key NSDictionary *colors = [NSDictionary dictionaryWithObjectsAndKeys:@”Red”, @”Color 1”, @”Green”, @”Color 2”, @”Blue”, @”Color 3”, nil]; NSString *firstColor = [colors objectForKey:@”Color 1”]; if ([colors objectForKey:@”Color 8”]) { // won’t make it here } Thursday, January 7, 2010 50
  • 68. NSMutableDictionary • NSMutableDictionary subclasses NSDictionary • Common NSMutableDictionary methods + (NSMutableDictionary *)dictionary; - (void)setObject:(id)object forKey:(id)key; - (void)removeObjectForKey:(id)key; - (void)removeAllObjects; NSMutableDictionary *colors = [NSMutableDictionary dictionary]; [colors setObject:@”Orange” forKey:@”HighlightColor”]; Thursday, January 7, 2010 51
  • 69. NSSet • Unordered collection of objects • Common NSSet methods ! + setWithObjects:(id)firstObj, ...; // nil terminated ! - (unsigned)count; ! - (BOOL)containsObject:(id)object; Thursday, January 7, 2010 52
  • 70. NSMutableSet • NSMutableSet subclasses NSSet • Common NSMutableSet methods ! + (NSMutableSet *)set; ! - (void)addObject:(id)object; ! - (void)removeObject:(id)object; ! - (void)removeAllObjects; ! - (void)intersectSet:(NSSet *)otherSet; ! - (void)minusSet:(NSSet *)otherSet; Thursday, January 7, 2010 53
  • 71. Enumeration • Consistent way of enumerating over objects in collections • Use with NSArray, NSDictionary, NSSet, etc. NSArray *array = ... ; // assume an array of People objects // old school Person *person; int count = [array count]; for (i = 0; i < count; i++) { person = [array objectAtIndex:i]; NSLog([person description]); } // new school for (Person *person in array) { NSLog([person description]); } Thursday, January 7, 2010 54
  • 72. NSNumber • In Objective-C, you typically use standard C number types • NSNumber is used to wrap C number types as objects • Subclass of NSValue • No mutable equivalent! • Common NSNumber methods + (NSNumber *)numberWithInt:(int)value; + (NSNumber *)numberWithDouble:(double)value; - (int)intValue; - (double)doubleValue; Thursday, January 7, 2010 55
  • 73. Other Classes • NSData / NSMutableData ■ Arbitrary sets of bytes • NSDate / NSCalendarDate ■ Times and dates Thursday, January 7, 2010 56
  • 74. Getting some objects • Until we talk about memory management: ■ Use class factory methods ■ NSString’s +stringWithFormat: ■ NSArray’s +array ■ NSDictionary’s +dictionary ■ Or any method that returns an object except alloc/init or copy. Thursday, January 7, 2010 57
  • 75. More ObjC Info? • http://developer.apple.com/documentation/Cocoa/ Conceptual/ObjectiveC • Concepts in Objective C are applicable to any other OOP language Thursday, January 7, 2010 58