SlideShare une entreprise Scribd logo
1  sur  142
Télécharger pour lire hors ligne
Objective-C
 L’ABC del Linguaggio




 Giuseppe Arici § The Preacher
Giuseppe Arici
   Apple iOS & Mac OS X Addicted Developer
    Superpartes Innovation Campus & H-Farm

   Group Founder & Cocoa Preacher




                                                                   m
    # Pragma Mark ― pragmamark.org




                                                                 co
                                                       pe y ;)
                                                             ci.
                                                    sep bo
                                                         ari
                                                 giu Fan
   A Social & Lazy Connected Node




                                                → ot a
    [ tt | in | fb | * ] / giuseppe.arici




                                             ard n
                                            I'm
   Mail Forwarder & Spammer



                                            vC
    giuseppe.arici@gmail.com


                                                                iOS Bootcamp
Alzi la mano chi ...




     ?
                       iOS Bootcamp
Agenda



       ia & Fi losofia
 Stor
            tica & Fisica
M   atema




                            iOS Bootcamp
The History


              iOS Bootcamp
40 Years !




1971   1981       1991     2001     2011


                                  iOS Bootcamp
Dennis Ritchie @ Bell Labs




1969 - 1973


                                iOS Bootcamp
Alan Kay @ Xerox PARC




1972 - 1980


                    iOS Bootcamp
Steve Jobs & Steve Wozniak @ 




    1976


                          iOS Bootcamp
Apple Team @ Xerox PARC




   1979


                     iOS Bootcamp
Brad Cox & Tom Love @ ITT




     1980


                       iOS Bootcamp
Byte Magazine # Agosto1981




     1981


                        iOS Bootcamp
The “OOPC”




1982


              iOS Bootcamp
StepStone (formerly PPI)




     1983


                           iOS Bootcamp
OOP An Evolutionary Approach




          1986


                        iOS Bootcamp
Steve Jobs ⚡ John Sculley




       1985


                            iOS Bootcamp
NeXT Computer (∡28°)




      1986


                       iOS Bootcamp
NeXT ® Objective-C ⚐ StepStone




            1988


                         iOS Bootcamp
WWW & Doom & Mathematica

     ☢NeXTcube




                 1991


                        iOS Bootcamp
NeXT + Sun = OpenStep API
   NSObject




           “Java Was Strongly Influenced by Objective-C”
     Patrick Naughton, co-creator of Java Programming Language


                                1993


                                                                 iOS Bootcamp
NeXT ⊆ Apple




        1996


               iOS Bootcamp
Code Name “Rhapsody”




            1997


                       iOS Bootcamp
Mac OS X v10.0




            2001


                   iOS Bootcamp
clas          fast
                          se               enu                 @p
                                                me
                            xte                    rat            rop
                                                      ion
                                  nsio                    / fo
                                                              r
                                                                     ert
                                      ns                       in            y
                                                                                     Objective-C 2.0




               2006




                                   gar
                  opt                  bag
                      ion                 ec               new
                                            olle
                          al   pro               c  tion                run
                                                           @               tim
                                  toc                          OS                e
                                           ol                       X
iOS Bootcamp
The iPhone




             2007


                    iOS Bootcamp
The iPhone SDK




                 2008


                   iOS Bootcamp
Chris Lattner @ 
    Source: http://nondot.org/sabre/Resume.html

    Director and Architect, Low-Level Tools
    September 2011 - Ongoing

    Senior Manager and Architect, Low-Level Tools
    June 2010 - September 2011

    Senior Manager of Compilers and Low-Level Tools, Compiler Architect
    September 2009 - June 2010

    Manager of Compilers and Low-Level Tools, Compiler Architect
    July 2008 - September 2009

    LLVM Compiler Group Manager and Compiler Architect
    December 2006 - July 2008

    Senior Compiler Engineer and Tech Lead
    June 2005 - December 2006




                                                   2005


                                                             iOS Bootcamp
LLVM Compiler Infrastructure




    Source:The Architecture of Open Source Applications http://www.aosabook.org/en/llvm.html

                                                                                               2007


                                                                                                      iOS Bootcamp
Clang (Static Analyzer)




                          2009


                          iOS Bootcamp
^ Blocks & GCD




                 2009


                 iOS Bootcamp
Xcode 4




           2010


          iOS Bootcamp
Automatic Reference Counting




    * Messaggio Promozionale: http://www.whymca.org/intervento/automatic-reference-counting
                                                                                                2011


                                                                                              iOS Bootcamp
@s                                                                             Enu
                                                                                                 ms
                 ynt                                                                                  wit                     Ob
                                                                                   hes                    hfi                         j ec
                                                                                      ize                   xed                          t lit
                                                                                                                  und
                                                                                             by                      e rlyi                      era
                                                                                                def
                                                                                                    aul                       ng
                                                                                                                                    typ
                                                                                                                                                    ls
                                                                                                        t                                e




                 WWDC 2012 Session 405: Modern Objective-C by Patrick C. Beard
                                                                                                                                                             Modern Objective-C




                                                                                              Un
                Sub                                                                              ord                     Box
                                                                                 scr                ere
                                                                                    ip                  dm                  ed
                                                                                      ting                eth                             Exp
                                                                                             me                   od                            res
                                                                                                                     dec
               2012




                                                                                                  tho                    l   ara                   sio
                                                                                                     ds                         t  ion                n  s
                                                                                                                                      s
iOS Bootcamp
TIOBE: Top 10 July 2012




Source: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

                                                                           iOS Bootcamp
TIOBE: Long Term Trends




 Source: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

                                                                            iOS Bootcamp
TIOBE: Objective-C


       Programming Language of the Year


                        2011

Source: http://www.tiobe.com/index.php/paperinfo/tpci/Objective-C.html

                                                                         iOS Bootcamp
Ipse dixit: Tom Love ⚔ C++

           “Objective-C and C++ both started from C, but they
           went in two very different directions. Which approach
           do you prefer now?

           Tom: There’s the successful direction, and then
           there’s the approach that Bjarne took with C++.
           In one case, it was a small, simple — dare I say,
           elegant — programming language that was very
           crisp and well defined. In the other case it was a
           pretty ugly, complicated, difficult language that
           had some really troublesome features. I think
           those are the distinctions between the two.”




                                                         iOS Bootcamp
Intervallo !?




                iOS Bootcamp
The Language


               iOS Bootcamp
Fundamental Laws




                   iOS Bootcamp
A strict superset of C
•   Objective-C is not inspired by C language like Java or C#

•   Objective-C is a strict superset of the C language

•   Objective-C has only added some concepts and their
    associated keywords

•   Like with C++, a well-written C program should be
    compile-able as Objective-C

•   Unlike with C++, there is no risk of incompatibility
    between C names and Objective-C keywords




                                                           iOS Bootcamp
A strict superset of C

                                                                  @
@"" @( ) @[ ] @{ }        @private
@catch                    @property
@class                    @protected
@defs                     @protocol
@dynamic                  @public
@encode                   @required
@end                      @selector
@finally                   @synchronized
@implementation           @synthesize                             SEL     BOOL
@interface                @throw                                  IMP     YES
                                                                  nil     NO




                                                                                     f
                                                                                   de
@optional                 @try




                                                                                 pe
                                                                  Nil     id




                                                                               ty
 in        byref     readwrite   copy




                                                                                       s
                                                                                    er
                                                             ts
                                                   co i n
 out       oneway    readonly    nonatomic

                                                          ex




                                                                                    et
                                                lar ble




                                                                                   m
                                                       nt
 inout     getter    assign      strong                           self




                                                                                 ra
                                            i cu i l a




                                                                               pa
                                          rt va


 bycopy    setter    retain      weak                             super




                                                                            en
                                        pa a




                                                                          dd
                                                                          hi
                                                                                 iOS Bootcamp
Requirements


               iOS Bootcamp
Objective-C
       void, char, int, long, float                        function pointer
                      c {array}                     sizeof    signed, unsigned
  c "string"
                                                           function
  typedef, enum, union                                  const, auto, static, extern

 # preprocessor                                                        (type)casting
                                                        malloc, free
      C Standard Library
                                                         for, do, while
if, else, switch, case                       int main(int argc, const char * argv[])

  format specifiers %d %s            stack vs heap
                                                           *, &, [ ]
         member selection . ->
                                 Struct             break, continue, goto

                                                                            iOS Bootcamp
Objective-C
                    Polymorphism
       Message passing               Subclass
                                           Method
   Class                              Delegation
Instance Variable                               Superclass
                                      Method overriding
 Inheritance
 Dynamic dispatch / binding
                                 Encapsulation
              Abstraction     Interface / Protocol

                                                     iOS Bootcamp
Class


        iOS Bootcamp
Bad News
                 NO namespaces ☹
                 Use prefix instead !
NSObject, NSString, ...

UIButton, UILabel, ...

ABAddressBook, ABRecord, ...

// Pragma Mark
PMDeveloper, PMEvent, ...


            Draft Proposal for Namespaces in Objective-C: @namespace @using
      http://www.optshiftk.com/2012/04/draft-proposal-for-namespaces-in-objective-c/

                                                                                       iOS Bootcamp
Class

                          #import


          @interface                @implementation

//     Person.h                //     Person.m

                               #import "Person.h"

@interface Person : NSObject   @implementation Person

@end                           @end



                                                        iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end




                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{base types
    NSInteger _balance;
}
  import
- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end




                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}  class definition
-
         start
  (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end




                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}         class name
- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end




                                            iOS Bootcamp
Class @interface

                   extends
#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}                     parent class
- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end




                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

             instance
- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;
             variables
@end




                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

- (NSInteger) withdraw:(NSInteger)amount;
- (void) deposit:(NSInteger)amount;

@end
            methods
           declarations


                                            iOS Bootcamp
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}
     class definition
-   (NSInteger) withdraw:(NSInteger)amount;
-          end
    (void) deposit:(NSInteger)amount;

@end




                                              iOS Bootcamp
Class @implementation
#import "BankAccount.h"

@implementation BankAccount

- (id) init {
    self = [super init];
    return self;
}

- (NSInteger) withdraw:(NSInteger)amount {
    return amount;
}

- (void) deposit:(NSInteger)amount {
    _balance += amount;
}
@end



                                             iOS Bootcamp
Class @implementation
#import "BankAccount.h"

@implementation BankAccount
     interface
-   (id) init {
      import[super
      self =         init];
     return self;
}

- (NSInteger) withdraw:(NSInteger)amount {
    return amount;
}

- (void) deposit:(NSInteger)amount {
     _balance += amount;
}
@end



                                             iOS Bootcamp
Class @implementation
#import "BankAccount.h"

@implementation BankAccount

- (id) init {
  class implementation
    self = [super init];
    return self;
}
          start
- (NSInteger) withdraw:(NSInteger)amount {
    return amount;
}

- (void) deposit:(NSInteger)amount {
     _balance += amount;
}
@end



                                             iOS Bootcamp
Class @implementation
#import "BankAccount.h"

@implementation BankAccount

- (id) init {
    self = [super init];
    return self;
}

- (NSInteger) withdraw:(NSInteger)amount {
    return amount;
}
                                         methods with
- (void) deposit:(NSInteger)amount {
    _balance += amount;                     bodies
}
@end



                                                    iOS Bootcamp
Class @implementation
#import "BankAccount.h"

@implementation BankAccount

- (id) init {
    self = [super init];
    return self;
}

- (NSInteger) withdraw:(NSInteger)amount {
    return amount;
}
     class implementation
-   (void) deposit:(NSInteger)amount   {
               end
      _balance += amount;
}
@end



                                             iOS Bootcamp
@class directive
•   @class directive provides minimal information about a class.

•   @class indicates that the name you are referencing is a class!

•   The use of the @class is known as a forward declaration
// Rectangle.h                     // Rectangle.m
#import "Shape.h"                  #import "Rectangle.h"

@class Point;                      #import "Point.h"

@interface Rectangle : Shape       @implementation Rectangle

- (Point *)center;                 - (Point *)center {
                                       // ...
                                   }
@end                               @end


                                                           iOS Bootcamp
Instance Variable Declaration
@interface MyClass : NSObject
{
    @private
    // Can only be accessed by instances of MyClass
    NSInteger _privateIvar1;
    NSString *_privateIvar2;

    @protected // Default
    // Can only be accessed by instances of MyClass or MyClass's subclasses
    NSInteger _protectedIvar1;
    NSString *_protectedIvar2;

    @package // 64-bit only
    // Can be accessed by any object in the framework in which MyClass is defined
    NSInteger _packageIvar1;
    NSString *_packageIvar2;;

    @public // Never use it !
    // Can be accessed by any object               scope
    NSInteger _publicVar1;
    NSString *_publicVar2;                        qualifiers
}




                                                                          iOS Bootcamp
Method & Message


               iOS Bootcamp
Method Declaration
- (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



                 In other languages, might be:

bool MyClass::writeToFileAtomically(std::string path, bool flag); // C++

public virtual bool WriteToFileAtomically(string path, bool flag); // C#

public boolean writeToFileAtomically(String path, boolean flag); // Java

public function writeToFileAtomically(path, flag) // PHP

def writeToFileAtomically(self, path, flag): # Python

def writeToFileAtomically(path, flag) # Ruby




                                                                   iOS Bootcamp
Method Declaration
 - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



  method scope
Can be either:
  + for a class method
  - for an instance method
Methods are always public !
  “Private” methods defined in implementation


                                                         iOS Bootcamp
Method Declaration
 - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



    return type
Can be any valid data type, including:
   void returns nothing
   id a pointer to an object of any class
   NSString * a pointer to an NSString
   BOOL a boolean (YES or NO)


                                                         iOS Bootcamp
Method Declaration
 - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



                        method name
The method name is composed of all labels
Colons precede arguments, but are part of the method name


              writeTofile:atomically:



                                                         iOS Bootcamp
Method Declaration
 - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



           argument type            argument name
Arguments come after or within the method name


Variadic methods can take variable arguments
  - (id)stringWithFormat:(NSString *)format ...
          stdarg: va_list va_start() va_arg() va_end()




                                                         iOS Bootcamp
@selector
  SEL callback = @selector(writeToFile:atomically:);



 data type            macro to
for selector        create selector
Conceptually similar to function pointer
Useful for callback type behavior

 if ([helper respondsToSelector:callback]) {
     [helper performSelector:callback withObject:arguments];
 }



                                                         iOS Bootcamp
Message Passing
•   Methods are invoked by passing messages

•   Messages aren’t bound to method implementations until
    runtime. The compiler converts a message expression:
    [receiver message];


•   into a call on a messaging function objc_msgSend:
    objc_msgSend(receiver, selector);


•   Any arguments passed in the message are also handed to
    objc_msgSend:
    objc_msgSend(receiver, selector. arg1, arg2, ...);



                                                         iOS Bootcamp
Message Passing
[data writeToFile:@"/tmp/data.txt" atomically:YES];



                 In other languages, might be:

data->writeToFileAtomically("/tmp/data.txt", true); // C++

data.WriteToFileAtomically("/tmp/data.txt", true); // C#

data.writeToFileAtomically("/tmp/data.txt", true); // Java

$data->writeToFileAtomically("/tmp/data.txt", TRUE); // PHP

data.writeToFileAtomically('/tmp/data.txt', True) # Python

data.writeToFileAtomically '/tmp/data.txt', true # Ruby




                                                              iOS Bootcamp
Message Passing
 [data writeToFile:@"/tmp/data.txt" atomically:YES];



             square brackets syntax
Nested Message Passing: [ [ ] [ ] [ [ ] ] ]

 [[store data] writeToFile:[@"/tmp/data.txt" lowercaseString]
                atomically:[[PMOption sharedOption] writeMode]
                  encoding:NSUTF8StringEncoding
                     error:&error];




                                                         iOS Bootcamp
Message Forwarding
•   In Objective C is very common to do message forwarding
    (a strategy pattern)

•   When an object receives a message and it does not have a
    corresponding method, it can delegates the task to another
    object

- (void)forwardInvocation:(NSInvocation*)invocation {
    SEL sel = [invocation selector];
    if ([helper respondsToSelector:sel]) {
        [invocation invokeWithTarget:helper];
    } else {
        [self doesNotRecognizeSelector:sel];
    }
}



                                                        iOS Bootcamp
Message Terminology
•   Message expression
    [data writeToFile:@"/tmp/data.txt" atomically:YES];


•   Message
    [data writeToFile:@"/tmp/data.txt" atomically:YES];


•   Selector
    [data writeToFile:@"/tmp/data.txt" atomically:YES];


•   Method
    { ... } // The code selected by a message



                                                          iOS Bootcamp
Self & Super
•   Methods have implicit reference to owning object called self
    (similar to Java and C# this, but self is a l-value)

•   Additionally have access to superclass methods using super



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadData];
}




                                                         iOS Bootcamp
Object
Life Cycle

             iOS Bootcamp
Object Construction
• NSObject defines class method called alloc
  •     Dynamically allocates memory for object on the heap

  •     Returns new instance of receiving class

      BankAccount *account = [BankAccount alloc];


• NSObject defines instance method called init
  •     Implemented by subclasses to initialize instance after memory has been allocated

  •     Subclasses commonly define several initializers (default indicated in documentation)

      BankAccount *account = [[BankAccount alloc] init];


• alloc and init calls are always nested into single line
      BankAccount *account = [[BankAccount alloc] init];


                                                                                    iOS Bootcamp
Object Construction
     initWith…

•    Needs to call super

•    Setup instance variables

•    Returns self

    - (id) init {
        self = [super init];
        if (self) {
           _myInstanceVariable = @"Pragma Mark !";
        }
        return self;
    }



                                                     iOS Bootcamp
Object Destruction
     dealloc

•    Never call explicitly

•    Release all retained or copied instance variables (* if not ARC)

•    Calls [super dealloc] (* if not ARC)
    - (void)saveThis:(id)object {
        if (_myInstanceVariable != object ) {
            [_myInstanceVariable release];
            _myInstanceVariable = [object retain];
        }
    }

    - (void)dealloc {
        [_myInstanceVariable release];
        [super dealloc];
    }




                                                             iOS Bootcamp
Memory
Management

             iOS Bootcamp
Memory Management
• Manual Reference Counting
 •   Higher level abstraction than malloc / free

 •   Straightforward approach, but must adhere to conventions and rules


• Automatic Reference Counting (ARC)
 •   Makes memory management the job of the compiler (and runtime)

 •   Available for: partially iOS 4+ or OS X 10.6+ / fully iOS 5+ or OS X 10.7+


• Garbage Collection
 •   Only available for OS X 10.5+

 •   Not available on iOS due to performance concerns


                                                                                  iOS Bootcamp
Manual Reference Counting
(Only) objective-C objects are reference counted:

 •   Objects start with retain count of 1

 •   Increased with retain

 •   Decreased with release, autorelease

 •   When count equals 0, runtime invokes dealloc


          1                2              1               0

  alloc           retain        release         release

                                               dealloc
                                                     iOS Bootcamp
Objects you create
    For objects you create with [[SomeClass alloc] init] or
    [myInstance copy] (without autoreleasing):

•   Retain should not need to be called

•   Release when you are done using it in the {code block}

- (void)someMethod {
    NSArray *someArray = [[NSArray alloc] init];
    _myInstanceVariable = someArray;
}

- (void)dealloc {
    [_myInstanceVariable release];
    [super dealloc];
}


                                                          iOS Bootcamp
Objects you don’t create
    For objects you don’t create (e.g. get from methods):

•   Retain only when saving to instance (or static) variable

•   Release only if you retained it by saving it (as in above case)


- (void)someMethod {
    id anObject = [someArray objectAtIndex:0];
    _myInstanceVariable = [anObject retain];
}

- (void)dealloc {
    [_myInstanceVariable release];
    [super dealloc];
}


                                                             iOS Bootcamp
Autorelease
What if you create an object and you are returning it from a
method, how would you be able to release it?
- (NSArray *)objects {
    NSArray *myArray = [[NSArray alloc] init];      ✇
}
    return myArray;
                                                  Leak !

                                                   ☠
- (NSArray *)objects {
    NSArray *myArray = [[NSArray alloc] init];
    return [myArray release];
}                                                Crash !
- (NSArray *)objects {
    NSArray *myArray = [[NSArray alloc] init];      ☺
    return [myArray autorelease];
}                                                 Right !
                                                       iOS Bootcamp
Autorelease
•   Instead of explicitly releasing something, you mark it for a
    later release

•   An object called autorelease pool manages a set of
    objects to release when the pool is released

•   Add an object to the release pool by calling autorelease

@autoreleasepool {
    // code goes here
}

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// code goes here
[pool release];



                                                          iOS Bootcamp
Autorelease
•   Autorelease is NOT a Garbage Collector !
    It is deterministic ⌚

•   Objects returned from methods are understood to be
    autoreleased if name is not in implicit retained set
    (alloc, new, init or copy)

•   If you spawn your own thread, you’ll have to create your
    own NSAutoreleasePool

•   Stack based: autorelease pools can be nested


                   Friday Q&A 2011-09-02: Let's Build NSAutoreleasePool
    http://www.mikeash.com/pyblog/friday-qa-2011-09-02-lets-build-nsautoreleasepool.html

                                                                                    iOS Bootcamp
Memory Management Rule



Everything that increases the retain count with
alloc, [mutable]copy[WithZone:] or retain is in
   charge of the corresponding [auto]release.


                          From C++ to Objective-C
         http://pierre.chachatelier.fr/programmation/objective-c.php

                                                                       iOS Bootcamp
Automatic Reference Counting

 “Automatic Reference Counting (ARC) in Objective-C
 makes memory management the job of the compiler. By
 enabling ARC with the new Apple LLVM compiler, you
 will never need to type retain or release again,
 dramatically simplifying the development process, while
 reducing crashes and memory leaks. The compiler has a
 complete understanding of your objects, and releases
 each object the instant it is no longer used, so apps run
 as fast as ever, with predictable, smooth performance.”
          (Apple, “iOS 5 for developers” – http://developer.apple.com/technologies/ios5)




                                                                                  iOS Bootcamp
Automatic Reference Counting
•   The Rule is still valid, but it is managed by the compiler

•   No more retain, release, autorelease nor dealloc

•   New lifetime qualifiers for objects, which includes zeroing
    weak references (only available on iOS 5+ & OS X 10.7+)

•   Apple provides a migration tool which is build into Xcode




                                                           iOS Bootcamp
Automatic Reference Counting




   * Messaggio Auto-Promozionale: http://www.whymca.org/intervento/automatic-reference-counting



                                                                                                  iOS Bootcamp
Property


           iOS Bootcamp
Property
•   Objective-C 2.0 introduced new syntax for defining
    accessor code:
    •   Much less verbose, less error prone

    •   Highly configurable

    •   Automatically generates accessor code


•   Complementary to existing conventions and technologies:
    •   Key-Value Coding (KVC)

    •   Key-Value Observing (KVO)

    •   Cocoa Bindings

    •   Core Data                               Simplifying Accessors

                                                                iOS Bootcamp
Property Declaration
@property(attributes) type name;


          Attribute                 Impacts

   readonly / readwrite             Mutability

      setter / getter                  API

         nonatomic                 Concurrency

 assign / retain / copy
   weak / strong (* in ARC)          Storage



                                                 iOS Bootcamp
Property Declaration
@property(attributes) type name;


          Attribute                        Impacts

   readonly / readwrite                    Mutability

      getter / setter                           API

         nonatomic                       Concurrency

 assign / retain / copy
   weak / strong (* in ARC)                    Storage

@property(readonly) NSString *accountNumber;

                                                         iOS Bootcamp
Property Declaration
@property(attributes) type name;


          Attribute                        Impacts

   readonly / readwrite                    Mutability

      setter / getter                         API

         nonatomic                        Concurrency

 assign / retain / copy
   weak / strong (* in ARC)                 Storage

@property(getter=isActive) BOOL active;

                                                        iOS Bootcamp
Property Declaration
@property(attributes) type name;


          Attribute                        Impacts

   readonly / readwrite                    Mutability

      getter / setter                         API

         nonatomic                       Concurrency

 assign / retain / copy
   weak / strong (* in ARC)                 Storage

@property(nonatomic, retain) NSDate *createdAt;

                                                        iOS Bootcamp
Property Declaration
@property(attributes) type name;


          Attribute                        Impacts

   readonly / readwrite                    Mutability

      getter / setter                         API

         nonatomic                       Concurrency

 assign / retain / copy
   weak / strong (* in ARC)                 Storage

@property(readwrite, copy) NSString *accountNumber;

                                                        iOS Bootcamp
Retain Cycles

Parent                   Child
              retain




1                        1
              retain




                                 iOS Bootcamp
Retain Cycles

Parent                   Child
              retain




0                        1
              assign




                                 iOS Bootcamp
Retain Cycles
                         assign

            X       unsafe_unretained
nil                                                release


            X
                          weak




         Controller      ☺nil            View
      as View Delegate
                                          New with ARC in
                                        iOS 5+ & OS X 10.7+
                                                     iOS Bootcamp
Property @interface
#import <Foundation/Foundation.h>

@interface BankAccount : NSObject {

    NSString *_accountNumber;
    NSDecimalNumber *_balance;
    NSDecimalNumber *_fees;
    BOOL _active;
}

@property(readwrite, copy) NSString *accountNumber;
@property(readwrite, retain) NSDecimalNumber *balance;
@property(readonly) NSDecimalNumber *fees;
@property(getter=isActive) BOOL active;

@end




                                                         iOS Bootcamp
Property @interface
#import <Foundation/Foundation.h>

@interface BankAccount : NSObject {
    // No more instance variable declarations !


                        New in
}                 iOS 4+ & OS X 10.6+
@property(readwrite, copy) NSString *accountNumber;
@property(readwrite, retain) NSDecimalNumber *balance;
@property(readonly) NSDecimalNumber *fees;
@property(getter=isActive) BOOL active;

@end




                                                         iOS Bootcamp
Property @implementation
#import "BankAccount.h"

@implementation BankAccount

//...

@synthesize   accountNumber = _accountNumber;
@synthesize   balance = _balance;
@synthesize   fees = _fees;
@synthesize   active = _active;

//...

@end




                                                iOS Bootcamp
Property @implementation
#import "BankAccount.h"

@implementation BankAccount

// No more @synthesize statements !



                           New in
                          Xcode 4.4+
                              (WWDC 2012)
//...

@end




                                            iOS Bootcamp
Property Access
•   Generated properties are standard methods

•   Accessed through normal messaging syntax
      id value = [object property];
      [object setProperty:newValue];



•   Objective-C 2.0 property access via dot syntax
      id value = object.property;
      object.property = newValue;



•   Dot notation is just syntactic sugar. Still uses accessor
    methods. Doesn't get/set values directly

                                                           iOS Bootcamp
Protocol


           iOS Bootcamp
Protocol
•   List of method declarations
    •   Not associated with a particular class

    •   Conformance, not class, is important


•   Useful in defining
    •   Methods that others are expected to implement

    •   Declaring an interface while hiding its particular class

    •   Capturing similarities among classes that aren't hierarchically related



                                                      Java / C# Interface done
                                                          Objective-C style

                                                                                  iOS Bootcamp
Protocol
•   Defining a Protocol
@protocol NSCoding

- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;

@end




•   Adopting a Protocol
@interface Person : NSObject<NSCoding> {
    NSString *_name;
}
// method & property declarations
@end


                                             iOS Bootcamp
Protocol
•   Conforming to a Protocol
@implementation Person

// Partial implementation of conforming Person class

- (id)initWithCoder:(NSCoder *)coder {
    if (self = [super init]) {
        _name = [coder decodeObjectForKey:@"name"];
        [_name retain];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
     [coder encodeObject:_name forKey:@"name"];
}
@end


                                                       iOS Bootcamp
@required & @optional
•   Protocols methods are required by default

•   Can be relaxed with @optional directive
@protocol SomeProtocol

- (void)requiredMethod;

@optional

- (void)anOptionalMethod;
- (void)anotherOptionalMethod;

@required

- (void)anotherRequiredMethod;

@end


                                                iOS Bootcamp
Category & Extension


                  iOS Bootcamp
Category
•   Add new methods to existing classes
    •   Alternative to subclassing

    •   Defines new methods and can override existing

    •   Does not define new instance variables (* in case use Associative References)

    •   Becomes part of the class definition (Inherited by subclasses)


•   Can be used as organizational tool

•   Often used in defining “private” methods

                                                          Extending Object
                                                              Features

                                                                                       iOS Bootcamp
Category
•   Defining and using a Category
// File NSString+PMAddition.h
@interface NSString (PMAddition)
- (NSString *)trim;
@end



// File NSString+PMAddition.m
@implementation NSString (PMAddition)
- (NSString *)trim {
    NSCharacterSet *cs;
     cs = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    return [self stringByTrimmingCharactersInSet:charSet];
}
@end


#import "NSString+PMAddition.h"
// ...
NSString *string = @"   A string to be trimmed";
NSLog(@"Trimmed string: '%@'", [string trim]);


                                                               iOS Bootcamp
Class Extension
•   Objective-C 2.0 adds ability to define anonymous categories
    •   Class extension is unnamed

    •   Treated as class interface continuations


•   Useful for implementing required “private” API

•   Compiler enforces methods are implemented




                                                   Unnamed Categories

                                                                 iOS Bootcamp
Class Extension
•   Interface

@interface Person : NSObject {

      NSUInteger _age;
}

- (NSUInteger)age;

@end




                                   iOS Bootcamp
Class Extension
•   Implementation + “Private” Method

@interface Person ()

- (void)setAge:(NSUInteger)age;

@end

@implementation Person

- (NSUInteger)age {
    return _age;
}

- (void)setAge:(NSUInteger)age {
    _age = age;
}

@end


                                        iOS Bootcamp
Exception & Block


                    iOS Bootcamp
Exception
 •   Very few uses for @try, @catch, @throw, and @finally

 •   Reserve the use of exceptions for programming or
     unexpected runtime errors (very different from Java / C#)

 •   NSError and the Cocoa error-delivery mechanism are
     the recommended way to communicate expected errors
 @try {
     // do something
 }
 @catch (NSException *e) {
     // handle exception
 }
 @finally {
     // close resources
 }


- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;


                                                              iOS Bootcamp
Block
•   Similar to standard C functions but, in addition to
    executable code, blocks may also contain variable bindings

•   Also called closures (or lambdas), because they close
    around variables in their scope
                                               New in
•   A nonstandard extension to C         iOS 4+ & OS X 10.6+
•   Used as anonymous functions

int (^myBlock)(int) = ^(int num) { return num * multipier; };



[objects sortUsingComparator:^(id firstObject, id secondObject) {
     return [firstObject compare:secondObject];
    }];



                                                                iOS Bootcamp
Base Type


            iOS Bootcamp
Dynamic and Static Typing
•   Dynamically-typed object:
        id anObject;

    •    Just id

    •    Not id * (unless you really, really mean it: pointer to pointer)


•   Statically-typed object:
        BankAccount *anObject;


•   Objective-C provides compile-time type checking

•   Objective-C always uses dynamic binding



                                                                            iOS Bootcamp
The nil object pointer
•   Test for nil explicitly:
     if (nil == person) return; // Yoda Syntax <(-_-)>


•   Or implicitly:
     if (!person) return;


•   Can use in assignments and as arguments if expected
     person = nil;
     [button setTarget: nil];


•   Sending a message to nil? NO Problem !
     person = nil;
     [person talk];


                                                         iOS Bootcamp
The BOOL typedef
•   When Objective-C was developed, C had no boolean type
    (C99 introduced one)

•   Objective-C uses a typedef to define BOOL as a type
     BOOL flag = NO;


•   Macro included for initialization and comparison:
    YES and NO
     if (flag) { // ...
     if (!flag) { // ...

     if (YES == flag) { // ... use !!flag
     if (NO == flag) { // ...

     flag = YES;
     flag = 1;


                                                        iOS Bootcamp
Foundation Framework


                 iOS Bootcamp
Framework
•   Frameworks are functionally similar to shared libraries

•   A compiled object that can be dynamically loaded into a
    program's address space at runtime

•   Frameworks add associated resources, header files, and
    documentation




                                                     iOS Bootcamp
Foundation.framework
•   Values and Strings

•   Collections

•   User defaults

•   Archiving

•   Notifications

•   Tasks, timers, threads

•   File system, I/O, bundles

•   URL, XML, Scanner


                                iOS Bootcamp
NSObject
•   Root Class                   @interface BankAccount : NSObject


•   Implements many basics
    •   Memory management
         [anObject retain];

    •   Introspection
         if ([anObject isKindOfClass:[Person class]]) {

    •   Object equality

         if ([obj1 isEqual:obj2]) { // NOT obj1 == obj2

    •   String representation (description is like toString() in Java or ToString() in C#)

         NSLog(@"%@", [anObject description]);
         NSLog(@"%@", anObject); // call description

                                                                                             iOS Bootcamp
NSString @
•   General-purpose Unicode string support

•   NSString objects are conceptually UTF-16 endianness

•   Consistently used in Cocoa instead of “const char *”

•   Objective-C string literals start with @

•   NSString is immutable, NSMutableString is mutable

     const char *cString = "Pragma Mark"; // C string
     NSString *nsString = @"バンザイ"; // NSString @

     cString = [nsString UTF8String];
     nsString = [NSString stringWithCString:cString
                    encoding:NSUTF8StringEncoding];


                                                        iOS Bootcamp
Format Strings
•   Similar to printf, but with %@ added for objects:
     NSString *title = @"The Preacher";
     NSString *whoami = [NSString stringWithFormat:
                            @"I am %@ !", title];

     // whoami would be set to:
     // I am The Preacher !


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

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




                                                        iOS Bootcamp
Collections
•   NSArray - ordered collection of objects

•   NSDictionary - collection of key-value pairs

•   NSSet - unordered collection of unique objects

•   Immutable and mutable versions
    •    Immutable collections can be shared without side effect

    •    Mutable objects typically carry a performance overhead


        NSDictionary *dic;
        dic = [[NSDictionary alloc] initWithObjectsAndKeys:
              @"ga", @"username", @"42", @"password", nil];
              //nil to signify end of objects and keys.



                                                                   iOS Bootcamp
Collections
•   Collections can contain only objects

•   Wrap primitive types in NSNumber or NSValue

•   New literal syntax for:
                                                                         New in
    •    array @[ obj, ... ]
                                                                        Xcode 4.4+
    •    dictionary @{ key : obj, ...}                                        (WWDC 2012)


    •    boxed expressions @( number or c string ) As a shortcut, number literals can be boxed without using the ( )



        NSArray *a = @[@"42", @42, @"42", @3.14];

        NSDictionary *d = @{ @1 : @"black", @2 : @"white"};



                                                                                                             iOS Bootcamp
Fast Enumeration
•   Added in Objective-C 2.0

•   for in similar to Java / C# foreach

•   Use with NSArray, NSDictionary, NSSet or with any object
    of class that adopt the NSFastEnumeration protocol
     NSArray *people; // ...

     // Old school
     for (int i = 0; i < [people count]; ++i) {
         Person *person = [people objectAtIndex:i];
     }

     // New school
     for (Person *person in people) {
     }


                                                      iOS Bootcamp
Summary


          iOS Bootcamp
Objective-C
•   Fully C, Fully Object-Oriented, Powerful Dynamic Runtime

•   Objective-C 2.0 added many useful new features:
    •   Garbage Collection for Mac OS X apps

    •   Properties, Improved Categories & Protocols


•   Objective-C LLVM continues evolution:
    •   Blocks (Closures)

    •   Automatic Reference Counting

    •   Synthesize by default for properties

    •   New literals




                                                      iOS Bootcamp
Objective-C Reference Books




                        iOS Bootcamp
Are you bored !?




The Objective-C Programming Language
Objective-C Runtime Programming Guide
                                        iOS Bootcamp
Questions ?




  giuseppe.arici@gmail.com
thepreacher@pragmamark.org
                             iOS Bootcamp
What’s NeXT !?
                          Objective-C
               ded      Runtime's Delight      Me
          Re y
                                                  tap
       ent or
            loa
                                                      rog
     em em



                                                 Ob ra
                                                     jec mm
  nag C: M




                                                        tive ing
                                                            -C in
Ma AR




                                                                         h
                                                              al D k &
                                                                     atc
                                                                  isp
                                                           ntr loc
Co
  de




                                                       Ce t ^B
 W Gen
   ith er




                                                   and ou
      LLV atio




                                                 Gr All ab
         M n
                       Never Say Never Again
                        The Objective-C++


                                                             iOS Bootcamp
One More Thing !




                   iOS Bootcamp
Thanks ☺




giuseppearici.com   pragmamark.org

                                     iOS Bootcamp

Contenu connexe

Similaire à Objective-C: A 40-Year History

Session 1 - Introduction to iOS 7 and SDK
Session 1 -  Introduction to iOS 7 and SDKSession 1 -  Introduction to iOS 7 and SDK
Session 1 - Introduction to iOS 7 and SDKVu Tran Lam
 
OTA WIreless Deployment
OTA WIreless DeploymentOTA WIreless Deployment
OTA WIreless Deploymentalekseyn
 
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...OPITZ CONSULTING Deutschland
 
iOS development made easy
iOS development made easyiOS development made easy
iOS development made easyAdrian Thompson
 
iOS Einstieg und Ausblick
iOS Einstieg und AusblickiOS Einstieg und Ausblick
iOS Einstieg und AusblickStefan Scheidt
 
iPhone Os开发简介
iPhone Os开发简介iPhone Os开发简介
iPhone Os开发简介Hao Peiqiang
 
Sqlpo Presentation
Sqlpo PresentationSqlpo Presentation
Sqlpo Presentationsandook
 
RubyMotion Gets A Cool New Friend: mruby on iOS
RubyMotion Gets A Cool New Friend: mruby on iOSRubyMotion Gets A Cool New Friend: mruby on iOS
RubyMotion Gets A Cool New Friend: mruby on iOSJoseph Ku
 
Scott Forstall 簡介
Scott Forstall 簡介Scott Forstall 簡介
Scott Forstall 簡介Roca Chang
 
iPhone Development For .Net Dev
iPhone Development For .Net DeviPhone Development For .Net Dev
iPhone Development For .Net DevAlex Hung
 
Cutting platform costs with Y3
Cutting platform costs with Y3Cutting platform costs with Y3
Cutting platform costs with Y3YobiDrive
 
Introduction to iPhone Programming
Introduction to iPhone Programming Introduction to iPhone Programming
Introduction to iPhone Programming Vu Tran Lam
 
Trends in the software industry
Trends in the software industryTrends in the software industry
Trends in the software industryLi SUN
 
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2Plone in the Cloud - an on-demand CMS hosted on Amazon EC2
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2Jazkarta, Inc.
 
A lap around monotouch
A lap around monotouchA lap around monotouch
A lap around monotouchmecurioJ
 
Yet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationYet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationNao Tokui
 
Mamona presentation at linuxtag
Mamona presentation at linuxtagMamona presentation at linuxtag
Mamona presentation at linuxtagkeesj
 

Similaire à Objective-C: A 40-Year History (20)

Session 1 - Introduction to iOS 7 and SDK
Session 1 -  Introduction to iOS 7 and SDKSession 1 -  Introduction to iOS 7 and SDK
Session 1 - Introduction to iOS 7 and SDK
 
OTA WIreless Deployment
OTA WIreless DeploymentOTA WIreless Deployment
OTA WIreless Deployment
 
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
 
The apple book
The apple bookThe apple book
The apple book
 
iOS development made easy
iOS development made easyiOS development made easy
iOS development made easy
 
iOS Einstieg und Ausblick
iOS Einstieg und AusblickiOS Einstieg und Ausblick
iOS Einstieg und Ausblick
 
iPhone Os开发简介
iPhone Os开发简介iPhone Os开发简介
iPhone Os开发简介
 
Sqlpo Presentation
Sqlpo PresentationSqlpo Presentation
Sqlpo Presentation
 
RubyMotion Gets A Cool New Friend: mruby on iOS
RubyMotion Gets A Cool New Friend: mruby on iOSRubyMotion Gets A Cool New Friend: mruby on iOS
RubyMotion Gets A Cool New Friend: mruby on iOS
 
Scott Forstall 簡介
Scott Forstall 簡介Scott Forstall 簡介
Scott Forstall 簡介
 
iPhone Development For .Net Dev
iPhone Development For .Net DeviPhone Development For .Net Dev
iPhone Development For .Net Dev
 
Fll programming 101_nxt_g
Fll programming 101_nxt_gFll programming 101_nxt_g
Fll programming 101_nxt_g
 
Cutting platform costs with Y3
Cutting platform costs with Y3Cutting platform costs with Y3
Cutting platform costs with Y3
 
Introduction to iPhone Programming
Introduction to iPhone Programming Introduction to iPhone Programming
Introduction to iPhone Programming
 
Trends in the software industry
Trends in the software industryTrends in the software industry
Trends in the software industry
 
applet using java
applet using javaapplet using java
applet using java
 
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2Plone in the Cloud - an on-demand CMS hosted on Amazon EC2
Plone in the Cloud - an on-demand CMS hosted on Amazon EC2
 
A lap around monotouch
A lap around monotouchA lap around monotouch
A lap around monotouch
 
Yet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationYet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa Communication
 
Mamona presentation at linuxtag
Mamona presentation at linuxtagMamona presentation at linuxtag
Mamona presentation at linuxtag
 

Dernier

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
"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
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 

Dernier (20)

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
"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
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
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)
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 

Objective-C: A 40-Year History

  • 1. Objective-C L’ABC del Linguaggio Giuseppe Arici § The Preacher
  • 2. Giuseppe Arici  Apple iOS & Mac OS X Addicted Developer Superpartes Innovation Campus & H-Farm  Group Founder & Cocoa Preacher m # Pragma Mark ― pragmamark.org co pe y ;) ci. sep bo ari giu Fan  A Social & Lazy Connected Node → ot a [ tt | in | fb | * ] / giuseppe.arici ard n I'm  Mail Forwarder & Spammer vC giuseppe.arici@gmail.com iOS Bootcamp
  • 3. Alzi la mano chi ... ? iOS Bootcamp
  • 4. Agenda ia & Fi losofia  Stor tica & Fisica M atema iOS Bootcamp
  • 5. The History iOS Bootcamp
  • 6. 40 Years ! 1971 1981 1991 2001 2011 iOS Bootcamp
  • 7. Dennis Ritchie @ Bell Labs 1969 - 1973 iOS Bootcamp
  • 8. Alan Kay @ Xerox PARC 1972 - 1980 iOS Bootcamp
  • 9. Steve Jobs & Steve Wozniak @  1976 iOS Bootcamp
  • 10. Apple Team @ Xerox PARC 1979 iOS Bootcamp
  • 11. Brad Cox & Tom Love @ ITT 1980 iOS Bootcamp
  • 12. Byte Magazine # Agosto1981 1981 iOS Bootcamp
  • 13. The “OOPC” 1982 iOS Bootcamp
  • 14. StepStone (formerly PPI) 1983 iOS Bootcamp
  • 15. OOP An Evolutionary Approach 1986 iOS Bootcamp
  • 16. Steve Jobs ⚡ John Sculley 1985 iOS Bootcamp
  • 17. NeXT Computer (∡28°) 1986 iOS Bootcamp
  • 18. NeXT ® Objective-C ⚐ StepStone 1988 iOS Bootcamp
  • 19. WWW & Doom & Mathematica ☢NeXTcube 1991 iOS Bootcamp
  • 20. NeXT + Sun = OpenStep API NSObject “Java Was Strongly Influenced by Objective-C” Patrick Naughton, co-creator of Java Programming Language 1993 iOS Bootcamp
  • 21. NeXT ⊆ Apple 1996 iOS Bootcamp
  • 22. Code Name “Rhapsody” 1997 iOS Bootcamp
  • 23. Mac OS X v10.0 2001 iOS Bootcamp
  • 24. clas fast se enu @p me xte rat rop ion nsio / fo r ert ns in y Objective-C 2.0 2006 gar opt bag ion ec new olle al pro c tion run @ tim toc OS e ol X iOS Bootcamp
  • 25. The iPhone 2007 iOS Bootcamp
  • 26. The iPhone SDK 2008 iOS Bootcamp
  • 27. Chris Lattner @  Source: http://nondot.org/sabre/Resume.html Director and Architect, Low-Level Tools September 2011 - Ongoing Senior Manager and Architect, Low-Level Tools June 2010 - September 2011 Senior Manager of Compilers and Low-Level Tools, Compiler Architect September 2009 - June 2010 Manager of Compilers and Low-Level Tools, Compiler Architect July 2008 - September 2009 LLVM Compiler Group Manager and Compiler Architect December 2006 - July 2008 Senior Compiler Engineer and Tech Lead June 2005 - December 2006 2005 iOS Bootcamp
  • 28. LLVM Compiler Infrastructure Source:The Architecture of Open Source Applications http://www.aosabook.org/en/llvm.html 2007 iOS Bootcamp
  • 29. Clang (Static Analyzer) 2009 iOS Bootcamp
  • 30. ^ Blocks & GCD 2009 iOS Bootcamp
  • 31. Xcode 4 2010 iOS Bootcamp
  • 32. Automatic Reference Counting * Messaggio Promozionale: http://www.whymca.org/intervento/automatic-reference-counting 2011 iOS Bootcamp
  • 33. @s Enu ms ynt wit Ob hes hfi j ec ize xed t lit und by e rlyi era def aul ng typ ls t e WWDC 2012 Session 405: Modern Objective-C by Patrick C. Beard Modern Objective-C Un Sub ord Box scr ere ip dm ed ting eth Exp me od res dec 2012 tho l ara sio ds t ion n s s iOS Bootcamp
  • 34. TIOBE: Top 10 July 2012 Source: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html iOS Bootcamp
  • 35. TIOBE: Long Term Trends Source: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html iOS Bootcamp
  • 36. TIOBE: Objective-C Programming Language of the Year 2011 Source: http://www.tiobe.com/index.php/paperinfo/tpci/Objective-C.html iOS Bootcamp
  • 37. Ipse dixit: Tom Love ⚔ C++ “Objective-C and C++ both started from C, but they went in two very different directions. Which approach do you prefer now? Tom: There’s the successful direction, and then there’s the approach that Bjarne took with C++. In one case, it was a small, simple — dare I say, elegant — programming language that was very crisp and well defined. In the other case it was a pretty ugly, complicated, difficult language that had some really troublesome features. I think those are the distinctions between the two.” iOS Bootcamp
  • 38. Intervallo !? iOS Bootcamp
  • 39. The Language iOS Bootcamp
  • 40. Fundamental Laws iOS Bootcamp
  • 41. A strict superset of C • Objective-C is not inspired by C language like Java or C# • Objective-C is a strict superset of the C language • Objective-C has only added some concepts and their associated keywords • Like with C++, a well-written C program should be compile-able as Objective-C • Unlike with C++, there is no risk of incompatibility between C names and Objective-C keywords iOS Bootcamp
  • 42. A strict superset of C @ @"" @( ) @[ ] @{ } @private @catch @property @class @protected @defs @protocol @dynamic @public @encode @required @end @selector @finally @synchronized @implementation @synthesize SEL BOOL @interface @throw IMP YES nil NO f de @optional @try pe Nil id ty in byref readwrite copy s er ts co i n out oneway readonly nonatomic ex et lar ble m nt inout getter assign strong self ra i cu i l a pa rt va bycopy setter retain weak super en pa a dd hi iOS Bootcamp
  • 43. Requirements iOS Bootcamp
  • 44. Objective-C void, char, int, long, float function pointer c {array} sizeof signed, unsigned c "string" function typedef, enum, union const, auto, static, extern # preprocessor (type)casting malloc, free C Standard Library for, do, while if, else, switch, case int main(int argc, const char * argv[]) format specifiers %d %s stack vs heap *, &, [ ] member selection . -> Struct break, continue, goto iOS Bootcamp
  • 45. Objective-C Polymorphism Message passing Subclass Method Class Delegation Instance Variable Superclass Method overriding Inheritance Dynamic dispatch / binding Encapsulation Abstraction Interface / Protocol iOS Bootcamp
  • 46. Class iOS Bootcamp
  • 47. Bad News NO namespaces ☹ Use prefix instead ! NSObject, NSString, ... UIButton, UILabel, ... ABAddressBook, ABRecord, ... // Pragma Mark PMDeveloper, PMEvent, ... Draft Proposal for Namespaces in Objective-C: @namespace @using http://www.optshiftk.com/2012/04/draft-proposal-for-namespaces-in-objective-c/ iOS Bootcamp
  • 48. Class #import @interface @implementation // Person.h // Person.m #import "Person.h" @interface Person : NSObject @implementation Person @end @end iOS Bootcamp
  • 49. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 50. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject {base types NSInteger _balance; } import - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 51. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } class definition - start (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 52. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } class name - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 53. Class @interface extends #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } parent class - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 54. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } instance - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; variables @end iOS Bootcamp
  • 55. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end methods declarations iOS Bootcamp
  • 56. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } class definition - (NSInteger) withdraw:(NSInteger)amount; - end (void) deposit:(NSInteger)amount; @end iOS Bootcamp
  • 57. Class @implementation #import "BankAccount.h" @implementation BankAccount - (id) init { self = [super init]; return self; } - (NSInteger) withdraw:(NSInteger)amount { return amount; } - (void) deposit:(NSInteger)amount { _balance += amount; } @end iOS Bootcamp
  • 58. Class @implementation #import "BankAccount.h" @implementation BankAccount interface - (id) init { import[super self = init]; return self; } - (NSInteger) withdraw:(NSInteger)amount { return amount; } - (void) deposit:(NSInteger)amount { _balance += amount; } @end iOS Bootcamp
  • 59. Class @implementation #import "BankAccount.h" @implementation BankAccount - (id) init { class implementation self = [super init]; return self; } start - (NSInteger) withdraw:(NSInteger)amount { return amount; } - (void) deposit:(NSInteger)amount { _balance += amount; } @end iOS Bootcamp
  • 60. Class @implementation #import "BankAccount.h" @implementation BankAccount - (id) init { self = [super init]; return self; } - (NSInteger) withdraw:(NSInteger)amount { return amount; } methods with - (void) deposit:(NSInteger)amount { _balance += amount; bodies } @end iOS Bootcamp
  • 61. Class @implementation #import "BankAccount.h" @implementation BankAccount - (id) init { self = [super init]; return self; } - (NSInteger) withdraw:(NSInteger)amount { return amount; } class implementation - (void) deposit:(NSInteger)amount { end _balance += amount; } @end iOS Bootcamp
  • 62. @class directive • @class directive provides minimal information about a class. • @class indicates that the name you are referencing is a class! • The use of the @class is known as a forward declaration // Rectangle.h // Rectangle.m #import "Shape.h" #import "Rectangle.h" @class Point; #import "Point.h" @interface Rectangle : Shape @implementation Rectangle - (Point *)center; - (Point *)center { // ... } @end @end iOS Bootcamp
  • 63. Instance Variable Declaration @interface MyClass : NSObject { @private // Can only be accessed by instances of MyClass NSInteger _privateIvar1; NSString *_privateIvar2; @protected // Default // Can only be accessed by instances of MyClass or MyClass's subclasses NSInteger _protectedIvar1; NSString *_protectedIvar2; @package // 64-bit only // Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1; NSString *_packageIvar2;; @public // Never use it ! // Can be accessed by any object scope NSInteger _publicVar1; NSString *_publicVar2; qualifiers } iOS Bootcamp
  • 64. Method & Message iOS Bootcamp
  • 65. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; In other languages, might be: bool MyClass::writeToFileAtomically(std::string path, bool flag); // C++ public virtual bool WriteToFileAtomically(string path, bool flag); // C# public boolean writeToFileAtomically(String path, boolean flag); // Java public function writeToFileAtomically(path, flag) // PHP def writeToFileAtomically(self, path, flag): # Python def writeToFileAtomically(path, flag) # Ruby iOS Bootcamp
  • 66. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; method scope Can be either: + for a class method - for an instance method Methods are always public ! “Private” methods defined in implementation iOS Bootcamp
  • 67. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; return type Can be any valid data type, including: void returns nothing id a pointer to an object of any class NSString * a pointer to an NSString BOOL a boolean (YES or NO) iOS Bootcamp
  • 68. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; method name The method name is composed of all labels Colons precede arguments, but are part of the method name writeTofile:atomically: iOS Bootcamp
  • 69. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; argument type argument name Arguments come after or within the method name Variadic methods can take variable arguments - (id)stringWithFormat:(NSString *)format ... stdarg: va_list va_start() va_arg() va_end() iOS Bootcamp
  • 70. @selector SEL callback = @selector(writeToFile:atomically:); data type macro to for selector create selector Conceptually similar to function pointer Useful for callback type behavior if ([helper respondsToSelector:callback]) { [helper performSelector:callback withObject:arguments]; } iOS Bootcamp
  • 71. Message Passing • Methods are invoked by passing messages • Messages aren’t bound to method implementations until runtime. The compiler converts a message expression: [receiver message]; • into a call on a messaging function objc_msgSend: objc_msgSend(receiver, selector); • Any arguments passed in the message are also handed to objc_msgSend: objc_msgSend(receiver, selector. arg1, arg2, ...); iOS Bootcamp
  • 72. Message Passing [data writeToFile:@"/tmp/data.txt" atomically:YES]; In other languages, might be: data->writeToFileAtomically("/tmp/data.txt", true); // C++ data.WriteToFileAtomically("/tmp/data.txt", true); // C# data.writeToFileAtomically("/tmp/data.txt", true); // Java $data->writeToFileAtomically("/tmp/data.txt", TRUE); // PHP data.writeToFileAtomically('/tmp/data.txt', True) # Python data.writeToFileAtomically '/tmp/data.txt', true # Ruby iOS Bootcamp
  • 73. Message Passing [data writeToFile:@"/tmp/data.txt" atomically:YES]; square brackets syntax Nested Message Passing: [ [ ] [ ] [ [ ] ] ] [[store data] writeToFile:[@"/tmp/data.txt" lowercaseString] atomically:[[PMOption sharedOption] writeMode] encoding:NSUTF8StringEncoding error:&error]; iOS Bootcamp
  • 74. Message Forwarding • In Objective C is very common to do message forwarding (a strategy pattern) • When an object receives a message and it does not have a corresponding method, it can delegates the task to another object - (void)forwardInvocation:(NSInvocation*)invocation { SEL sel = [invocation selector]; if ([helper respondsToSelector:sel]) { [invocation invokeWithTarget:helper]; } else { [self doesNotRecognizeSelector:sel]; } } iOS Bootcamp
  • 75. Message Terminology • Message expression [data writeToFile:@"/tmp/data.txt" atomically:YES]; • Message [data writeToFile:@"/tmp/data.txt" atomically:YES]; • Selector [data writeToFile:@"/tmp/data.txt" atomically:YES]; • Method { ... } // The code selected by a message iOS Bootcamp
  • 76. Self & Super • Methods have implicit reference to owning object called self (similar to Java and C# this, but self is a l-value) • Additionally have access to superclass methods using super - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self reloadData]; } iOS Bootcamp
  • 77. Object Life Cycle iOS Bootcamp
  • 78. Object Construction • NSObject defines class method called alloc • Dynamically allocates memory for object on the heap • Returns new instance of receiving class BankAccount *account = [BankAccount alloc]; • NSObject defines instance method called init • Implemented by subclasses to initialize instance after memory has been allocated • Subclasses commonly define several initializers (default indicated in documentation) BankAccount *account = [[BankAccount alloc] init]; • alloc and init calls are always nested into single line BankAccount *account = [[BankAccount alloc] init]; iOS Bootcamp
  • 79. Object Construction initWith… • Needs to call super • Setup instance variables • Returns self - (id) init { self = [super init]; if (self) { _myInstanceVariable = @"Pragma Mark !"; } return self; } iOS Bootcamp
  • 80. Object Destruction dealloc • Never call explicitly • Release all retained or copied instance variables (* if not ARC) • Calls [super dealloc] (* if not ARC) - (void)saveThis:(id)object { if (_myInstanceVariable != object ) { [_myInstanceVariable release]; _myInstanceVariable = [object retain]; } } - (void)dealloc { [_myInstanceVariable release]; [super dealloc]; } iOS Bootcamp
  • 81. Memory Management iOS Bootcamp
  • 82. Memory Management • Manual Reference Counting • Higher level abstraction than malloc / free • Straightforward approach, but must adhere to conventions and rules • Automatic Reference Counting (ARC) • Makes memory management the job of the compiler (and runtime) • Available for: partially iOS 4+ or OS X 10.6+ / fully iOS 5+ or OS X 10.7+ • Garbage Collection • Only available for OS X 10.5+ • Not available on iOS due to performance concerns iOS Bootcamp
  • 83. Manual Reference Counting (Only) objective-C objects are reference counted: • Objects start with retain count of 1 • Increased with retain • Decreased with release, autorelease • When count equals 0, runtime invokes dealloc 1 2 1 0 alloc retain release release dealloc iOS Bootcamp
  • 84. Objects you create For objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing): • Retain should not need to be called • Release when you are done using it in the {code block} - (void)someMethod { NSArray *someArray = [[NSArray alloc] init]; _myInstanceVariable = someArray; } - (void)dealloc { [_myInstanceVariable release]; [super dealloc]; } iOS Bootcamp
  • 85. Objects you don’t create For objects you don’t create (e.g. get from methods): • Retain only when saving to instance (or static) variable • Release only if you retained it by saving it (as in above case) - (void)someMethod { id anObject = [someArray objectAtIndex:0]; _myInstanceVariable = [anObject retain]; } - (void)dealloc { [_myInstanceVariable release]; [super dealloc]; } iOS Bootcamp
  • 86. Autorelease What if you create an object and you are returning it from a method, how would you be able to release it? - (NSArray *)objects { NSArray *myArray = [[NSArray alloc] init]; ✇ } return myArray; Leak ! ☠ - (NSArray *)objects { NSArray *myArray = [[NSArray alloc] init]; return [myArray release]; } Crash ! - (NSArray *)objects { NSArray *myArray = [[NSArray alloc] init]; ☺ return [myArray autorelease]; } Right ! iOS Bootcamp
  • 87. Autorelease • Instead of explicitly releasing something, you mark it for a later release • An object called autorelease pool manages a set of objects to release when the pool is released • Add an object to the release pool by calling autorelease @autoreleasepool { // code goes here } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // code goes here [pool release]; iOS Bootcamp
  • 88. Autorelease • Autorelease is NOT a Garbage Collector ! It is deterministic ⌚ • Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc, new, init or copy) • If you spawn your own thread, you’ll have to create your own NSAutoreleasePool • Stack based: autorelease pools can be nested Friday Q&A 2011-09-02: Let's Build NSAutoreleasePool http://www.mikeash.com/pyblog/friday-qa-2011-09-02-lets-build-nsautoreleasepool.html iOS Bootcamp
  • 89. Memory Management Rule Everything that increases the retain count with alloc, [mutable]copy[WithZone:] or retain is in charge of the corresponding [auto]release. From C++ to Objective-C http://pierre.chachatelier.fr/programmation/objective-c.php iOS Bootcamp
  • 90. Automatic Reference Counting “Automatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler. By enabling ARC with the new Apple LLVM compiler, you will never need to type retain or release again, dramatically simplifying the development process, while reducing crashes and memory leaks. The compiler has a complete understanding of your objects, and releases each object the instant it is no longer used, so apps run as fast as ever, with predictable, smooth performance.” (Apple, “iOS 5 for developers” – http://developer.apple.com/technologies/ios5) iOS Bootcamp
  • 91. Automatic Reference Counting • The Rule is still valid, but it is managed by the compiler • No more retain, release, autorelease nor dealloc • New lifetime qualifiers for objects, which includes zeroing weak references (only available on iOS 5+ & OS X 10.7+) • Apple provides a migration tool which is build into Xcode iOS Bootcamp
  • 92. Automatic Reference Counting * Messaggio Auto-Promozionale: http://www.whymca.org/intervento/automatic-reference-counting iOS Bootcamp
  • 93. Property iOS Bootcamp
  • 94. Property • Objective-C 2.0 introduced new syntax for defining accessor code: • Much less verbose, less error prone • Highly configurable • Automatically generates accessor code • Complementary to existing conventions and technologies: • Key-Value Coding (KVC) • Key-Value Observing (KVO) • Cocoa Bindings • Core Data Simplifying Accessors iOS Bootcamp
  • 95. Property Declaration @property(attributes) type name; Attribute Impacts readonly / readwrite Mutability setter / getter API nonatomic Concurrency assign / retain / copy weak / strong (* in ARC) Storage iOS Bootcamp
  • 96. Property Declaration @property(attributes) type name; Attribute Impacts readonly / readwrite Mutability getter / setter API nonatomic Concurrency assign / retain / copy weak / strong (* in ARC) Storage @property(readonly) NSString *accountNumber; iOS Bootcamp
  • 97. Property Declaration @property(attributes) type name; Attribute Impacts readonly / readwrite Mutability setter / getter API nonatomic Concurrency assign / retain / copy weak / strong (* in ARC) Storage @property(getter=isActive) BOOL active; iOS Bootcamp
  • 98. Property Declaration @property(attributes) type name; Attribute Impacts readonly / readwrite Mutability getter / setter API nonatomic Concurrency assign / retain / copy weak / strong (* in ARC) Storage @property(nonatomic, retain) NSDate *createdAt; iOS Bootcamp
  • 99. Property Declaration @property(attributes) type name; Attribute Impacts readonly / readwrite Mutability getter / setter API nonatomic Concurrency assign / retain / copy weak / strong (* in ARC) Storage @property(readwrite, copy) NSString *accountNumber; iOS Bootcamp
  • 100. Retain Cycles Parent Child retain 1 1 retain iOS Bootcamp
  • 101. Retain Cycles Parent Child retain 0 1 assign iOS Bootcamp
  • 102. Retain Cycles assign X unsafe_unretained nil release X weak Controller ☺nil View as View Delegate New with ARC in iOS 5+ & OS X 10.7+ iOS Bootcamp
  • 103. Property @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSString *_accountNumber; NSDecimalNumber *_balance; NSDecimalNumber *_fees; BOOL _active; } @property(readwrite, copy) NSString *accountNumber; @property(readwrite, retain) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isActive) BOOL active; @end iOS Bootcamp
  • 104. Property @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { // No more instance variable declarations ! New in } iOS 4+ & OS X 10.6+ @property(readwrite, copy) NSString *accountNumber; @property(readwrite, retain) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isActive) BOOL active; @end iOS Bootcamp
  • 105. Property @implementation #import "BankAccount.h" @implementation BankAccount //... @synthesize accountNumber = _accountNumber; @synthesize balance = _balance; @synthesize fees = _fees; @synthesize active = _active; //... @end iOS Bootcamp
  • 106. Property @implementation #import "BankAccount.h" @implementation BankAccount // No more @synthesize statements ! New in Xcode 4.4+ (WWDC 2012) //... @end iOS Bootcamp
  • 107. Property Access • Generated properties are standard methods • Accessed through normal messaging syntax id value = [object property]; [object setProperty:newValue]; • Objective-C 2.0 property access via dot syntax id value = object.property; object.property = newValue; • Dot notation is just syntactic sugar. Still uses accessor methods. Doesn't get/set values directly iOS Bootcamp
  • 108. Protocol iOS Bootcamp
  • 109. Protocol • List of method declarations • Not associated with a particular class • Conformance, not class, is important • Useful in defining • Methods that others are expected to implement • Declaring an interface while hiding its particular class • Capturing similarities among classes that aren't hierarchically related Java / C# Interface done Objective-C style iOS Bootcamp
  • 110. Protocol • Defining a Protocol @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder; @end • Adopting a Protocol @interface Person : NSObject<NSCoding> { NSString *_name; } // method & property declarations @end iOS Bootcamp
  • 111. Protocol • Conforming to a Protocol @implementation Person // Partial implementation of conforming Person class - (id)initWithCoder:(NSCoder *)coder { if (self = [super init]) { _name = [coder decodeObjectForKey:@"name"]; [_name retain]; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:_name forKey:@"name"]; } @end iOS Bootcamp
  • 112. @required & @optional • Protocols methods are required by default • Can be relaxed with @optional directive @protocol SomeProtocol - (void)requiredMethod; @optional - (void)anOptionalMethod; - (void)anotherOptionalMethod; @required - (void)anotherRequiredMethod; @end iOS Bootcamp
  • 113. Category & Extension iOS Bootcamp
  • 114. Category • Add new methods to existing classes • Alternative to subclassing • Defines new methods and can override existing • Does not define new instance variables (* in case use Associative References) • Becomes part of the class definition (Inherited by subclasses) • Can be used as organizational tool • Often used in defining “private” methods Extending Object Features iOS Bootcamp
  • 115. Category • Defining and using a Category // File NSString+PMAddition.h @interface NSString (PMAddition) - (NSString *)trim; @end // File NSString+PMAddition.m @implementation NSString (PMAddition) - (NSString *)trim { NSCharacterSet *cs; cs = [NSCharacterSet whitespaceAndNewlineCharacterSet]; return [self stringByTrimmingCharactersInSet:charSet]; } @end #import "NSString+PMAddition.h" // ... NSString *string = @" A string to be trimmed"; NSLog(@"Trimmed string: '%@'", [string trim]); iOS Bootcamp
  • 116. Class Extension • Objective-C 2.0 adds ability to define anonymous categories • Class extension is unnamed • Treated as class interface continuations • Useful for implementing required “private” API • Compiler enforces methods are implemented Unnamed Categories iOS Bootcamp
  • 117. Class Extension • Interface @interface Person : NSObject { NSUInteger _age; } - (NSUInteger)age; @end iOS Bootcamp
  • 118. Class Extension • Implementation + “Private” Method @interface Person () - (void)setAge:(NSUInteger)age; @end @implementation Person - (NSUInteger)age { return _age; } - (void)setAge:(NSUInteger)age { _age = age; } @end iOS Bootcamp
  • 119. Exception & Block iOS Bootcamp
  • 120. Exception • Very few uses for @try, @catch, @throw, and @finally • Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java / C#) • NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors @try { // do something } @catch (NSException *e) { // handle exception } @finally { // close resources } - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error; iOS Bootcamp
  • 121. Block • Similar to standard C functions but, in addition to executable code, blocks may also contain variable bindings • Also called closures (or lambdas), because they close around variables in their scope New in • A nonstandard extension to C iOS 4+ & OS X 10.6+ • Used as anonymous functions int (^myBlock)(int) = ^(int num) { return num * multipier; }; [objects sortUsingComparator:^(id firstObject, id secondObject) { return [firstObject compare:secondObject]; }]; iOS Bootcamp
  • 122. Base Type iOS Bootcamp
  • 123. Dynamic and Static Typing • Dynamically-typed object: id anObject; • Just id • Not id * (unless you really, really mean it: pointer to pointer) • Statically-typed object: BankAccount *anObject; • Objective-C provides compile-time type checking • Objective-C always uses dynamic binding iOS Bootcamp
  • 124. The nil object pointer • Test for nil explicitly: if (nil == person) return; // Yoda Syntax <(-_-)> • Or implicitly: if (!person) return; • Can use in assignments and as arguments if expected person = nil; [button setTarget: nil]; • Sending a message to nil? NO Problem ! person = nil; [person talk]; iOS Bootcamp
  • 125. The BOOL typedef • When Objective-C was developed, C had no boolean type (C99 introduced one) • Objective-C uses a typedef to define BOOL as a type BOOL flag = NO; • Macro included for initialization and comparison: YES and NO if (flag) { // ... if (!flag) { // ... if (YES == flag) { // ... use !!flag if (NO == flag) { // ... flag = YES; flag = 1; iOS Bootcamp
  • 126. Foundation Framework iOS Bootcamp
  • 127. Framework • Frameworks are functionally similar to shared libraries • A compiled object that can be dynamically loaded into a program's address space at runtime • Frameworks add associated resources, header files, and documentation iOS Bootcamp
  • 128. Foundation.framework • Values and Strings • Collections • User defaults • Archiving • Notifications • Tasks, timers, threads • File system, I/O, bundles • URL, XML, Scanner iOS Bootcamp
  • 129. NSObject • Root Class @interface BankAccount : NSObject • Implements many basics • Memory management [anObject retain]; • Introspection if ([anObject isKindOfClass:[Person class]]) { • Object equality if ([obj1 isEqual:obj2]) { // NOT obj1 == obj2 • String representation (description is like toString() in Java or ToString() in C#) NSLog(@"%@", [anObject description]); NSLog(@"%@", anObject); // call description iOS Bootcamp
  • 130. NSString @ • General-purpose Unicode string support • NSString objects are conceptually UTF-16 endianness • Consistently used in Cocoa instead of “const char *” • Objective-C string literals start with @ • NSString is immutable, NSMutableString is mutable const char *cString = "Pragma Mark"; // C string NSString *nsString = @"バンザイ"; // NSString @ cString = [nsString UTF8String]; nsString = [NSString stringWithCString:cString encoding:NSUTF8StringEncoding]; iOS Bootcamp
  • 131. Format Strings • Similar to printf, but with %@ added for objects: NSString *title = @"The Preacher"; NSString *whoami = [NSString stringWithFormat: @"I am %@ !", title]; // whoami would be set to: // I am The Preacher ! • Also used for logging with NSLog macro: NSLog(@"I am a %@, I have %d items", [array className], [array count]); // would log something like: // I am a NSArray, I have 42 items iOS Bootcamp
  • 132. Collections • NSArray - ordered collection of objects • NSDictionary - collection of key-value pairs • NSSet - unordered collection of unique objects • Immutable and mutable versions • Immutable collections can be shared without side effect • Mutable objects typically carry a performance overhead NSDictionary *dic; dic = [[NSDictionary alloc] initWithObjectsAndKeys: @"ga", @"username", @"42", @"password", nil]; //nil to signify end of objects and keys. iOS Bootcamp
  • 133. Collections • Collections can contain only objects • Wrap primitive types in NSNumber or NSValue • New literal syntax for: New in • array @[ obj, ... ] Xcode 4.4+ • dictionary @{ key : obj, ...} (WWDC 2012) • boxed expressions @( number or c string ) As a shortcut, number literals can be boxed without using the ( ) NSArray *a = @[@"42", @42, @"42", @3.14]; NSDictionary *d = @{ @1 : @"black", @2 : @"white"}; iOS Bootcamp
  • 134. Fast Enumeration • Added in Objective-C 2.0 • for in similar to Java / C# foreach • Use with NSArray, NSDictionary, NSSet or with any object of class that adopt the NSFastEnumeration protocol NSArray *people; // ... // Old school for (int i = 0; i < [people count]; ++i) { Person *person = [people objectAtIndex:i]; } // New school for (Person *person in people) { } iOS Bootcamp
  • 135. Summary iOS Bootcamp
  • 136. Objective-C • Fully C, Fully Object-Oriented, Powerful Dynamic Runtime • Objective-C 2.0 added many useful new features: • Garbage Collection for Mac OS X apps • Properties, Improved Categories & Protocols • Objective-C LLVM continues evolution: • Blocks (Closures) • Automatic Reference Counting • Synthesize by default for properties • New literals iOS Bootcamp
  • 138. Are you bored !? The Objective-C Programming Language Objective-C Runtime Programming Guide iOS Bootcamp
  • 139. Questions ? giuseppe.arici@gmail.com thepreacher@pragmamark.org iOS Bootcamp
  • 140. What’s NeXT !? Objective-C ded Runtime's Delight Me Re y tap ent or loa rog em em Ob ra jec mm nag C: M tive ing -C in Ma AR h al D k & atc isp ntr loc Co de Ce t ^B W Gen ith er and ou LLV atio Gr All ab M n Never Say Never Again The Objective-C++ iOS Bootcamp
  • 141. One More Thing ! iOS Bootcamp
  • 142. Thanks ☺ giuseppearici.com pragmamark.org iOS Bootcamp