SlideShare a Scribd company logo
1 of 92
Download to read offline
Objective-C
The Apple Programming Language




    Giuseppe Arici § iOS Bootcamp @ ITIS
History


          iOS Bootcamp @ ITIS
Steve Jobs & Steve Wozniak @ 




    1976


                        iOS Bootcamp @ ITIS
Apple Team @ Xerox PARC




   1979


                   iOS Bootcamp @ ITIS
Steve Jobs ⚔ John Sculley




       1985


                      iOS Bootcamp @ ITIS
NeXT Computer (∡28°)




      1986


                  iOS Bootcamp @ ITIS
Brad Cox & Tom Love @ ITT




     1980


                     iOS Bootcamp @ ITIS
OOP An Evolutionary Approach




          1986


                      iOS Bootcamp @ ITIS
NeXT ® Objective-C ⚐ StepStone




            1988


                       iOS Bootcamp @ ITIS
WWW & Doom & Mathematica

      ☢NeXTcube




      This machine is a server.
     DO NOT POWER DOWN !!

                  1991


                                  iOS Bootcamp @ ITIS
NeXT ⊆ Apple




        1996


               iOS Bootcamp @ ITIS
Mac OS X v10.0




            2001


                   iOS Bootcamp @ ITIS
The iPhone




              2007


             iOS Bootcamp @ ITIS
The iPhone SDK




                    2008


                 iOS Bootcamp @ ITIS
Language


           iOS Bootcamp @ ITIS
The Commandments




               iOS Bootcamp @ ITIS
A strict superset of C
•   Objective-C is a strict superset of the C language

•   Objective-C is not inspired by C language like Java or C#

•   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 @ ITIS
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 @ ITIS
Requirements


               iOS Bootcamp @ ITIS
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 @ ITIS
Objective-C
                    Polymorphism
       Message passing               Subclass
                                           Method
   Class                              Delegation
Instance Variable                               Superclass
                                      Method overriding
 Inheritance
 Dynamic dispatch / binding
                                 Encapsulation
              Abstraction     Interface / Protocol

                                                iOS Bootcamp @ ITIS
Class


        iOS Bootcamp @ ITIS
Class

                          #import


          @interface                @implementation

//     Person.h                //     Person.m

                               #import "Person.h"

@interface Person : NSObject   @implementation Person

@end                           @end



                                                    iOS Bootcamp @ ITIS
Class @interface




                   iOS Bootcamp @ ITIS
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

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

@end




                                            iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
Class @interface

#import <Foundation/Foundation.h>

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

@end




                                            iOS Bootcamp @ ITIS
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 @ ITIS
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

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




                                            iOS Bootcamp @ ITIS
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

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

@end
            methods
           declarations


                                            iOS Bootcamp @ ITIS
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 @ ITIS
Class @interface

#import <Foundation/Foundation.h>

@interface BankAccount : NSObject
{
    NSInteger _balance;
}

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

@end




                                            iOS Bootcamp @ ITIS
Class @implementation




                   iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
Instance Variable Declaration
@interface MyClass : NSObject
{




}




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




}




                                                      iOS Bootcamp @ ITIS
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;




}




                                                                    iOS Bootcamp @ ITIS
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;




}




                                                                    iOS Bootcamp @ ITIS
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
    NSInteger _publicVar1;
    NSString *_publicVar2;

}




                                                                    iOS Bootcamp @ ITIS
@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 @ ITIS
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 @ ITIS
Method & Message


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




                                                   iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
Method Declaration
 - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag;



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




                                                    iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
Object Life Cycle


               iOS Bootcamp @ ITIS
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)

      [account init];


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


                                                                             iOS Bootcamp @ ITIS
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 (_instanceVariable != object ) {
            [_instanceVariable release];
            _instanceVariable = [object retain];
        }
    }

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




                                                        iOS Bootcamp @ ITIS
Memory Management


              iOS Bootcamp @ ITIS
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+, but depracated from 10.8+

 •   Not available on iOS due to performance concerns


                                                                        iOS Bootcamp @ ITIS
Memory Management




           Reference Count

                    iOS Bootcamp @ ITIS
Manual Reference Counting
(Only) Objective-C objects are reference counted:

•   Objects start with retain count of 1 when created

•   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 @ ITIS
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 @ ITIS
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 @ ITIS
The Memory Management Rule




Everything that increases the reference count
with alloc, copy, new 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 @ ITIS
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 @ ITIS
Automatic Reference Counting
•   The Rule is still valid, but it is managed by the compiler

•   No more retain, [auto]release nor dealloc

•   ARC is used in all new projects by default

•   Apple provides a migration tool which is build into Xcode




                                                      iOS Bootcamp @ ITIS
Property


           iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
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 @ ITIS
Property @interface
#import <Foundation/Foundation.h>

@interface BankAccount : NSObject {

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

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

@end




                                                   iOS Bootcamp @ ITIS
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, strong) NSDecimalNumber *balance;
@property(readonly) NSDecimalNumber *fees;
@property(getter=isActive) BOOL active;

@end




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

@implementation BankAccount

//...

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

//...

@end




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

@implementation BankAccount

// No more @synthesize statements !



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

@end




                                            iOS Bootcamp @ ITIS
Protocol


           iOS Bootcamp @ ITIS
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 @ ITIS
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 @ ITIS
Base Types


             iOS Bootcamp @ ITIS
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




                                                                            iOS Bootcamp @ ITIS
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 @ ITIS
@”NSString”
•   Objective-C string literals start with @

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

•   General-purpose Unicode string support

•   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 @ ITIS
Collections
•   NSArray - ordered collection of objects

•   NSDictionary - collection of key-value pairs

•   NSSet - unordered collection of unique objects

•   Immutable and mutable versions

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




                                                   iOS Bootcamp @ ITIS
Summary


          iOS Bootcamp @ ITIS
Objective-C




•   Objective-C is Fully C and Fully Object-Oriented

•   Objective-C supports both strong and weak typing

•   Objective-C is The Apple (only) Programming Language !


                                                  iOS Bootcamp @ ITIS
Questions




?           iOS Bootcamp @ ITIS
One More Thing !




                   iOS Bootcamp @ ITIS
NSLog(@”Thank you!”);




  giuseppe.arici@pragmamark.org

                             iOS Bootcamp @ ITIS

More Related Content

Viewers also liked

Viewers also liked (11)

Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Objective-C
Objective-CObjective-C
Objective-C
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Iphone programming: Objective c
Iphone programming: Objective cIphone programming: Objective c
Iphone programming: Objective c
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Similar to Objective-C @ ITIS (6)

C sharp chap2
C sharp chap2C sharp chap2
C sharp chap2
 
RheinJUG 2010 - Sprechen Sie Scala?
RheinJUG 2010 - Sprechen Sie Scala?RheinJUG 2010 - Sprechen Sie Scala?
RheinJUG 2010 - Sprechen Sie Scala?
 
Chtp408
Chtp408Chtp408
Chtp408
 
Core Java Training
Core Java TrainingCore Java Training
Core Java Training
 
Dimitry Solovyov - The imminent threat of functional programming
Dimitry Solovyov - The imminent threat of functional programmingDimitry Solovyov - The imminent threat of functional programming
Dimitry Solovyov - The imminent threat of functional programming
 
Mysterious c++
Mysterious c++Mysterious c++
Mysterious c++
 

Recently uploaded

Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
Wonjun Hwang
 

Recently uploaded (20)

AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 

Objective-C @ ITIS

  • 1. Objective-C The Apple Programming Language Giuseppe Arici § iOS Bootcamp @ ITIS
  • 2. History iOS Bootcamp @ ITIS
  • 3. Steve Jobs & Steve Wozniak @  1976 iOS Bootcamp @ ITIS
  • 4. Apple Team @ Xerox PARC 1979 iOS Bootcamp @ ITIS
  • 5. Steve Jobs ⚔ John Sculley 1985 iOS Bootcamp @ ITIS
  • 6. NeXT Computer (∡28°) 1986 iOS Bootcamp @ ITIS
  • 7. Brad Cox & Tom Love @ ITT 1980 iOS Bootcamp @ ITIS
  • 8. OOP An Evolutionary Approach 1986 iOS Bootcamp @ ITIS
  • 9. NeXT ® Objective-C ⚐ StepStone 1988 iOS Bootcamp @ ITIS
  • 10. WWW & Doom & Mathematica ☢NeXTcube This machine is a server. DO NOT POWER DOWN !! 1991 iOS Bootcamp @ ITIS
  • 11. NeXT ⊆ Apple 1996 iOS Bootcamp @ ITIS
  • 12. Mac OS X v10.0 2001 iOS Bootcamp @ ITIS
  • 13. The iPhone 2007 iOS Bootcamp @ ITIS
  • 14. The iPhone SDK 2008 iOS Bootcamp @ ITIS
  • 15. Language iOS Bootcamp @ ITIS
  • 16. The Commandments iOS Bootcamp @ ITIS
  • 17. A strict superset of C • Objective-C is a strict superset of the C language • Objective-C is not inspired by C language like Java or C# • 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 @ ITIS
  • 18. 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 @ ITIS
  • 19. Requirements iOS Bootcamp @ ITIS
  • 20. 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 @ ITIS
  • 21. Objective-C Polymorphism Message passing Subclass Method Class Delegation Instance Variable Superclass Method overriding Inheritance Dynamic dispatch / binding Encapsulation Abstraction Interface / Protocol iOS Bootcamp @ ITIS
  • 22. Class iOS Bootcamp @ ITIS
  • 23. Class #import @interface @implementation // Person.h // Person.m #import "Person.h" @interface Person : NSObject @implementation Person @end @end iOS Bootcamp @ ITIS
  • 24. Class @interface iOS Bootcamp @ ITIS
  • 25. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp @ ITIS
  • 26. 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 @ ITIS
  • 27. 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 @ ITIS
  • 28. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } class name - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp @ ITIS
  • 29. 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 @ ITIS
  • 30. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } instance - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; variables @end iOS Bootcamp @ ITIS
  • 31. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end methods declarations iOS Bootcamp @ ITIS
  • 32. 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 @ ITIS
  • 33. Class @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSInteger _balance; } - (NSInteger) withdraw:(NSInteger)amount; - (void) deposit:(NSInteger)amount; @end iOS Bootcamp @ ITIS
  • 34. Class @implementation iOS Bootcamp @ ITIS
  • 35. 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 @ ITIS
  • 36. 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 @ ITIS
  • 37. 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 @ ITIS
  • 38. 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 @ ITIS
  • 39. 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 @ ITIS
  • 40. 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 @ ITIS
  • 41. Instance Variable Declaration @interface MyClass : NSObject { } iOS Bootcamp @ ITIS
  • 42. Instance Variable Declaration @interface MyClass : NSObject { @private // Can only be accessed by instances of MyClass NSInteger _privateIvar1; NSString *_privateIvar2; } iOS Bootcamp @ ITIS
  • 43. 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; } iOS Bootcamp @ ITIS
  • 44. 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; } iOS Bootcamp @ ITIS
  • 45. 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 NSInteger _publicVar1; NSString *_publicVar2; } iOS Bootcamp @ ITIS
  • 46. @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 @ ITIS
  • 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 @ ITIS
  • 48. Method & Message iOS Bootcamp @ ITIS
  • 49. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; iOS Bootcamp @ ITIS
  • 50. 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 @ ITIS
  • 51. 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 @ ITIS
  • 52. 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 @ ITIS
  • 53. Method Declaration - (BOOL) writeToFile:(NSString *)path atomically:(BOOL)flag; argument type argument name Arguments come after or within the method name iOS Bootcamp @ ITIS
  • 54. 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 @ ITIS
  • 55. 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 @ ITIS
  • 56. Object Life Cycle iOS Bootcamp @ ITIS
  • 57. 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) [account init]; • alloc and init calls are always nested into single line BankAccount *account = [[BankAccount alloc] init]; iOS Bootcamp @ ITIS
  • 58. 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 (_instanceVariable != object ) { [_instanceVariable release]; _instanceVariable = [object retain]; } } - (void)dealloc { [_instanceVariable release]; [super dealloc]; } iOS Bootcamp @ ITIS
  • 59. Memory Management iOS Bootcamp @ ITIS
  • 60. 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+, but depracated from 10.8+ • Not available on iOS due to performance concerns iOS Bootcamp @ ITIS
  • 61. Memory Management Reference Count iOS Bootcamp @ ITIS
  • 62. Manual Reference Counting (Only) Objective-C objects are reference counted: • Objects start with retain count of 1 when created • 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 @ ITIS
  • 63. 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 @ ITIS
  • 64. 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 @ ITIS
  • 65. The Memory Management Rule Everything that increases the reference count with alloc, copy, new 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 @ ITIS
  • 66. 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 @ ITIS
  • 67. Automatic Reference Counting • The Rule is still valid, but it is managed by the compiler • No more retain, [auto]release nor dealloc • ARC is used in all new projects by default • Apple provides a migration tool which is build into Xcode iOS Bootcamp @ ITIS
  • 68. Property iOS Bootcamp @ ITIS
  • 69. 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 @ ITIS
  • 70. 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 @ ITIS
  • 71. 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 @ ITIS
  • 72. 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 @ ITIS
  • 73. 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 @ ITIS
  • 74. 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 @ ITIS
  • 75. 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 @ ITIS
  • 76. Property @interface #import <Foundation/Foundation.h> @interface BankAccount : NSObject { NSString *_accountNumber; NSDecimalNumber *_balance; NSDecimalNumber *_fees; BOOL _active; } @property(readwrite, copy) NSString *accountNumber; @property(readwrite, strong) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isActive) BOOL active; @end iOS Bootcamp @ ITIS
  • 77. 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, strong) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isActive) BOOL active; @end iOS Bootcamp @ ITIS
  • 78. Property @implementation #import "BankAccount.h" @implementation BankAccount //... @synthesize accountNumber = _accountNumber; @synthesize balance = _balance; @synthesize fees = _fees; @synthesize active = _active; //... @end iOS Bootcamp @ ITIS
  • 79. Property @implementation #import "BankAccount.h" @implementation BankAccount // No more @synthesize statements ! New in Xcode 4.4+ (WWDC 2012) //... @end iOS Bootcamp @ ITIS
  • 80. Protocol iOS Bootcamp @ ITIS
  • 81. 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 @ ITIS
  • 82. 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 @ ITIS
  • 83. Base Types iOS Bootcamp @ ITIS
  • 84. 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 iOS Bootcamp @ ITIS
  • 85. 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 @ ITIS
  • 86. @”NSString” • Objective-C string literals start with @ • Consistently used in Cocoa instead of “const char *” • General-purpose Unicode string support • 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 @ ITIS
  • 87. Collections • NSArray - ordered collection of objects • NSDictionary - collection of key-value pairs • NSSet - unordered collection of unique objects • Immutable and mutable versions NSDictionary *dic; dic = [[NSDictionary alloc] initWithObjectsAndKeys: @"ga", @"username", @"42", @"password", nil]; //nil to signify end of objects and keys. iOS Bootcamp @ ITIS
  • 88. Summary iOS Bootcamp @ ITIS
  • 89. Objective-C • Objective-C is Fully C and Fully Object-Oriented • Objective-C supports both strong and weak typing • Objective-C is The Apple (only) Programming Language ! iOS Bootcamp @ ITIS
  • 90. Questions ? iOS Bootcamp @ ITIS
  • 91. One More Thing ! iOS Bootcamp @ ITIS
  • 92. NSLog(@”Thank you!”); giuseppe.arici@pragmamark.org iOS Bootcamp @ ITIS