SlideShare une entreprise Scribd logo
1  sur  47
Objective-C
 a gentle introduction




 Gabriele Petronella
Outline

• From C to Objective-C
• OO in Objective-C
• Memory management
• Demo iOS

                   2
History, in brief
• Created in the early ‘80s by Brad Cox and
  Tom Love
• First Obj-C runtime in 1992
• Used by NeXT in the 90’s, later acquired by
  Apple
• Apple introduced Obj-C 2.0 in 2006
                     3
A C superset

• Obj-C adds Smalltalk-style messaging to C,
  used for OO operations
• C code is completely supported and used
  for any non OO operation
• Different philosophy w.r.t. C++

                     4
Obj-C vs C++
• C++ adds OO-programming, generic
  programming and metaprogramming to the
  C language
• Obj-C adds OO-programming, dynamic
  typing and reflection
• Bottom line C++ is geared toward
  compile-time features, whereas Obj-C is
  geared toward run-time features

                     5
A remarkable quote


“I made up the term ‘object-oriented’ and I
can tell you I did not have C++ in mind”
(Alan Kay, 1997)




                     6
Obj-C vs C (strings)
• C is fully supported, but some constructs are
  seldom used
• Strings are one example
  C string:       “string”
  Obj-C string:   @“string”
• Notice the @ sign

                       7
Pointers,
   pointers everywhere
• Typical C pointer usage
  int* intPtr;
  /* stuff */
  int anInt = *intPtr //dereferencing
• Usually pointers are dereferenced and we
  speak about the actual objects they point

                      8
Pointers,
   pointers everywhere
• In Obj-C that’s not the case: we declare
  pointers and we treat them as actual objects
• Anything you’ll want to do in Obj-C with an
  object will expect a pointer
• Obj-C itself will take care of accessing the
  actual objects under the hood.


                        9
Pointers,
   pointers everywhere
  NSString * s = @”Hi there”
• That’s convenient and that’s why we’ll tend
  to say that “s is an NSString” when it is
  actually a pointer to it
• But, please, never forget that a pointer is a
  pointer!


                        10
Pointers may trick you
  o1     o2                          o1    o2


                ptr1 = ptr2
  ptr1   ptr2                       ptr1   ptr2



• A typical beginners’ mistake is to think that
  the above assignment will provide a copy of
  o2, which is obvious not true since we’re
  assigning a pointer


                      11
Obj-C Objects Syntax

• The Obj-C syntax derives from Smalltalk
• Messages are sent to objects with a square
  brackets syntax, like for example
  [myObject doThis]
          an instance        a message

                        12
Message parameters
• A message can have parameters, of course
  [myObj doWithPar:par1
  otherPar:par2]
• The corresponding method’s signature will
  be
  doWithPar:otherPar:


                      13
Overloading
• Obj-C does not support overloading
• That’s not a big deal since methods use the
  infix notation
• The name of the method is mixed with it’s
  arguments
• This increases verbosity but also clarity
                      14
Writing vs Reading




Peter Hallam (Microsoft): What Do Programmers Really Do Anyway?
 http://blogs.msdn.com/b/peterhal/archive/2006/01/04/509302.aspx


                               15
Java vs Infix notation
• A real method call from an Android app
  PendingIntent.getActivity(context, 0, new
  Intent(), 0);

• In Obj-C it would look something like
  [PendingIntent activityWithContext:context
                requestCode:0
                   intent:[Intent new]
                    flags:0];
                      16
Java vs Infix notation
• A real method call from an Android app
  PendingIntent.getActivity(context, 0, new
  Intent(), 0);
                                          dafuq is this?!
• In Obj-C it would look something like
  [PendingIntent activityWithContext:context
                requestCode:0
                   intent:[Intent new]
                    flags:0];
                      16
Java vs Infix notation
• A real method call from an Android app
  PendingIntent.getActivity(context, 0, new
  Intent(), 0);
                                          dafuq is this?!
• In Obj-C it would look something like


                      16
Java vs Infix notation
• A real method call from an Android app
  PendingIntent.getActivity(context, 0, new
  Intent(), 0);
                                            dafuq is this?!
• In Obj-C it would look something like
  [PendingIntent activityWithContext:context
                         requestCode:0
                              intent:[Intent new]
 oh, a request code, I see...
                               flags:0];
                        16
Nesting calls

• Of course calls can be nested
  [politeObject sayHiTo:[anOtherObj name]];
  [[MyClass alloc] initWithName:[foo name]];




                      17
The nil case
• A non-valid object pointer has value nil
• Almost the same as a NULL pointer
• It is a form of zero, therefore the following
  code is (ugly but) legal
  obj = nil;
  if(obj) { /% do stuff %/ }

                        18
Talking to nil
• Any Java programmer here? Do you love
  NullPointerExceptions?
• In Obj-C there no such thing! That’s because
  sending a message to nil is legal

• What’s the value of obj2 after this code?
  obj1 = nil;
  obj2 = [obj1 doSomething];

                       19
Talking to nil

• Whether this is a good or a bad thing is a
  quasi-religious issue
• Cons: may cause silent failures difficult to
  track down
• Pros: allows flexibility

                      20
A touch of Class

• Classes are generally divided into two
  chunks of code
  @interface MyClass               defined in
  @end                             MyClass.h
  @implementation MyClass defined in
  @end                    MyClass.m


                       21
Inheritance

• The @interface declaration allows to
  specify a parent class
  @interface MyClass : NSObject
• NSObject is the Cocoa- base class- but it is
  (actually another one exists NSProxy
  not of our interest)



                         22
Methods declaration
• Methods are declared as follows
  @interface MyClass : NSObject
  + (MyClass *)myClassInstance;
  - (NSString *)sayHelloClass;
  @end
• Class methods starts with the + sign
• Instance methods with the - sign
                      23
Methods definition
• Methods are then defined in the
  @implementation section of the class
  @implementation MyClass
  - (NSString *)sayHelloClass {
      return @”Hello Class!”;
  }
  ...
  @end

                     24
Instance variables

• Instance vars are traditionally declared in
  the @interface section.
• However since iOS 5 it is allowed to
  declare them in the @implementation

• Consider that the @interface section is
  usually visible to other classes


                      25
Instance variables

• Here’s an example of ivars declaration
  @interface MyClass : NSObject {
    NSInteger anInteger;
    NSString * aString;
  }
  @end


                      26
Properties
• A property is a syntactical feature of Obj-C
  2.0, i.e. syntactic sugar for calling an accessor
  method. Example:
  NSString * name = [aPerson name];
  [aPerson setName:@”Mary”];
  equivalent to
  NSString * name = aPerson.name;
  aPerson.name = @”Mary”;
                        27
Properties declaration
• A property is generally declared in the
  @interface section as follows (< iOS4
  style)
  @property(nonatomic, retain)this changed *
                                NSString
                   * since iOS5
  name;


• The above line declares the accessor methods for
  the name variable.
• The options in the parenthesis define the
                         28
Properties definition
• The actual implementation of accessor
    methods is achieved like follows:
    @implementation MyClass
    @synthesize name;
    ...
•   The @synthesize keyword provides the
    implementation of the two methods
    - (NSString *)name
    - (void)setName:(NSString *)aName
                         29
Memory Management




        30
Memory Management
 alloc
         1




             30
Memory Management
 alloc       retain count
         1




                       30
Memory Management
 alloc       retain count   I care!
         1                            2




                       30
Memory Management
 alloc           retain count   I care!
             1                            2


   I care!


 I care!     5

   I care!




                           30
Memory Management
 alloc           retain count     I care!
             1                                   2


   I care!                        I don’t care any longer


 I care!                        me neither       1
             5

   I care!                        neither do I       neither do I




                           30
Memory Management
 alloc               retain count     I care!
               1                                     2


   I care!                            I don’t care any longer


 I care!                            me neither       1
               5

   I care!                            neither do I       neither do I



   I don’t care...
                     0

                               30
Memory Management
 alloc               retain count     I care!
               1                                     2


   I care!                            I don’t care any longer


 I care!                            me neither       1
               5

   I care!                            neither do I       neither do I



   I don’t care...         dealloc
                     0

                               30
The NARC Rule
• Every new, alloc, retain, copy (and
  mutableCopy) call MUST be balanced
  with a release
• This still holds even under ARC (Automatic
  Retain Count). The only difference is that
  the rule is automatically respected by the
  compiler for you.


                     31
Accessor methods and
memory management
- (void)setName:(NSString *)newName {
    if (newName != self->name) {
       /* release the old object*/
       [self->name release];
       /* retain the new one */
       self->name = [newName retain];
    }
}


                   32
Memory policies
• strong/retain: ‘normal’ reference that
  increases the retainCount
• copy: same as retain, but clones the object
• weak: ARC specific. Does not retain the
  object. Automatically nullify the pointer
• assign: pre-ARC. Same as weak but dåoes
  not automatically nullify the pointer!

                      33
Other options

• nonatomic/atomic: thread-safe or not.
  Default is atomic.
• getter/setter: defines the getter/setter
  names
• readonly/readwrite: whether produce the
  setter or not. Default is readwrite.


                       34
References


• Programming iOS 5 by Matt Neuborg
• Apple official documentation


                   35
Demo
Demo

Contenu connexe

Tendances

Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」techtalkdwango
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest
 
Audio SPU Presentation
Audio SPU PresentationAudio SPU Presentation
Audio SPU Presentationslantsixgames
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcescorehard_by
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operatorsNico Ludwig
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 CertificationsGiacomo Veneri
 

Tendances (20)

Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Audio SPU Presentation
Audio SPU PresentationAudio SPU Presentation
Audio SPU Presentation
 
Garbage
GarbageGarbage
Garbage
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Java unit i
Java unit iJava unit i
Java unit i
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Learn How to Master Solr1 4
Learn How to Master Solr1 4Learn How to Master Solr1 4
Learn How to Master Solr1 4
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resources
 
Pointers
PointersPointers
Pointers
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators
 
printf tricks
printf tricksprintf tricks
printf tricks
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 

En vedette

Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cMayank Jalotra
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective CAshiq Uz Zoha
 
iPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CiPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CIMC Institute
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof languagenicky_walters
 
I Phone Development Presentation
I Phone Development PresentationI Phone Development Presentation
I Phone Development PresentationAessam
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective csagaroceanic11
 
Iphone programming: Objective c
Iphone programming: Objective cIphone programming: Objective c
Iphone programming: Objective cKenny Nguyen
 
Hybrid vs Native Mobile App. Decide in 5 minutes!
Hybrid vs Native Mobile App. Decide in 5 minutes!Hybrid vs Native Mobile App. Decide in 5 minutes!
Hybrid vs Native Mobile App. Decide in 5 minutes!July Systems
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)Project Student
 
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScriptReact Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScriptKobkrit Viriyayudhakorn
 
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)Project Student
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 

En vedette (20)

Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
iPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CiPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-C
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof language
 
I Phone Development Presentation
I Phone Development PresentationI Phone Development Presentation
I Phone Development Presentation
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
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
 
Hybrid vs Native Mobile App. Decide in 5 minutes!
Hybrid vs Native Mobile App. Decide in 5 minutes!Hybrid vs Native Mobile App. Decide in 5 minutes!
Hybrid vs Native Mobile App. Decide in 5 minutes!
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)High Level Languages (Imperative, Object Orientated, Declarative)
High Level Languages (Imperative, Object Orientated, Declarative)
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScriptReact Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
 
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)
Appraisal (Self Assessment, Peer Assessment, 360 Degree Feedback)
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Objective-C
Objective-CObjective-C
Objective-C
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 

Similaire à Objective-C: a gentle introduction

Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CDataArt
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The BasicsNina Zakharenko
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingGiuseppe Arici
 
Automatic Reference Counting
Automatic Reference Counting Automatic Reference Counting
Automatic Reference Counting pragmamark
 
Jurczyk windows kernel reference count vulnerabilities. case study
Jurczyk   windows kernel reference count vulnerabilities. case studyJurczyk   windows kernel reference count vulnerabilities. case study
Jurczyk windows kernel reference count vulnerabilities. case studyDefconRussia
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
Artificial Intelligence, Machine Learning and Deep Learning
Artificial Intelligence, Machine Learning and Deep LearningArtificial Intelligence, Machine Learning and Deep Learning
Artificial Intelligence, Machine Learning and Deep LearningSujit Pal
 
Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYAnaya Medias Swiss
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
The View - The top 30 Development tips
The View - The top 30 Development tipsThe View - The top 30 Development tips
The View - The top 30 Development tipsBill Buchan
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]Kuba Břečka
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティスUnity Technologies Japan K.K.
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2Robin Aggarwal
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic libraryAdaCore
 

Similaire à Objective-C: a gentle introduction (20)

Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Eusecwest
EusecwestEusecwest
Eusecwest
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Automatic Reference Counting
Automatic Reference Counting Automatic Reference Counting
Automatic Reference Counting
 
Jurczyk windows kernel reference count vulnerabilities. case study
Jurczyk   windows kernel reference count vulnerabilities. case studyJurczyk   windows kernel reference count vulnerabilities. case study
Jurczyk windows kernel reference count vulnerabilities. case study
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
Artificial Intelligence, Machine Learning and Deep Learning
Artificial Intelligence, Machine Learning and Deep LearningArtificial Intelligence, Machine Learning and Deep Learning
Artificial Intelligence, Machine Learning and Deep Learning
 
Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONY
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
The View - The top 30 Development tips
The View - The top 30 Development tipsThe View - The top 30 Development tips
The View - The top 30 Development tips
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic library
 

Dernier

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Dernier (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Objective-C: a gentle introduction

  • 1. Objective-C a gentle introduction Gabriele Petronella
  • 2. Outline • From C to Objective-C • OO in Objective-C • Memory management • Demo iOS 2
  • 3. History, in brief • Created in the early ‘80s by Brad Cox and Tom Love • First Obj-C runtime in 1992 • Used by NeXT in the 90’s, later acquired by Apple • Apple introduced Obj-C 2.0 in 2006 3
  • 4. A C superset • Obj-C adds Smalltalk-style messaging to C, used for OO operations • C code is completely supported and used for any non OO operation • Different philosophy w.r.t. C++ 4
  • 5. Obj-C vs C++ • C++ adds OO-programming, generic programming and metaprogramming to the C language • Obj-C adds OO-programming, dynamic typing and reflection • Bottom line C++ is geared toward compile-time features, whereas Obj-C is geared toward run-time features 5
  • 6. A remarkable quote “I made up the term ‘object-oriented’ and I can tell you I did not have C++ in mind” (Alan Kay, 1997) 6
  • 7. Obj-C vs C (strings) • C is fully supported, but some constructs are seldom used • Strings are one example C string: “string” Obj-C string: @“string” • Notice the @ sign 7
  • 8. Pointers, pointers everywhere • Typical C pointer usage int* intPtr; /* stuff */ int anInt = *intPtr //dereferencing • Usually pointers are dereferenced and we speak about the actual objects they point 8
  • 9. Pointers, pointers everywhere • In Obj-C that’s not the case: we declare pointers and we treat them as actual objects • Anything you’ll want to do in Obj-C with an object will expect a pointer • Obj-C itself will take care of accessing the actual objects under the hood. 9
  • 10. Pointers, pointers everywhere NSString * s = @”Hi there” • That’s convenient and that’s why we’ll tend to say that “s is an NSString” when it is actually a pointer to it • But, please, never forget that a pointer is a pointer! 10
  • 11. Pointers may trick you o1 o2 o1 o2 ptr1 = ptr2 ptr1 ptr2 ptr1 ptr2 • A typical beginners’ mistake is to think that the above assignment will provide a copy of o2, which is obvious not true since we’re assigning a pointer 11
  • 12. Obj-C Objects Syntax • The Obj-C syntax derives from Smalltalk • Messages are sent to objects with a square brackets syntax, like for example [myObject doThis] an instance a message 12
  • 13. Message parameters • A message can have parameters, of course [myObj doWithPar:par1 otherPar:par2] • The corresponding method’s signature will be doWithPar:otherPar: 13
  • 14. Overloading • Obj-C does not support overloading • That’s not a big deal since methods use the infix notation • The name of the method is mixed with it’s arguments • This increases verbosity but also clarity 14
  • 15. Writing vs Reading Peter Hallam (Microsoft): What Do Programmers Really Do Anyway? http://blogs.msdn.com/b/peterhal/archive/2006/01/04/509302.aspx 15
  • 16. Java vs Infix notation • A real method call from an Android app PendingIntent.getActivity(context, 0, new Intent(), 0); • In Obj-C it would look something like [PendingIntent activityWithContext:context requestCode:0 intent:[Intent new] flags:0]; 16
  • 17. Java vs Infix notation • A real method call from an Android app PendingIntent.getActivity(context, 0, new Intent(), 0); dafuq is this?! • In Obj-C it would look something like [PendingIntent activityWithContext:context requestCode:0 intent:[Intent new] flags:0]; 16
  • 18. Java vs Infix notation • A real method call from an Android app PendingIntent.getActivity(context, 0, new Intent(), 0); dafuq is this?! • In Obj-C it would look something like 16
  • 19. Java vs Infix notation • A real method call from an Android app PendingIntent.getActivity(context, 0, new Intent(), 0); dafuq is this?! • In Obj-C it would look something like [PendingIntent activityWithContext:context requestCode:0 intent:[Intent new] oh, a request code, I see... flags:0]; 16
  • 20. Nesting calls • Of course calls can be nested [politeObject sayHiTo:[anOtherObj name]]; [[MyClass alloc] initWithName:[foo name]]; 17
  • 21. The nil case • A non-valid object pointer has value nil • Almost the same as a NULL pointer • It is a form of zero, therefore the following code is (ugly but) legal obj = nil; if(obj) { /% do stuff %/ } 18
  • 22. Talking to nil • Any Java programmer here? Do you love NullPointerExceptions? • In Obj-C there no such thing! That’s because sending a message to nil is legal • What’s the value of obj2 after this code? obj1 = nil; obj2 = [obj1 doSomething]; 19
  • 23. Talking to nil • Whether this is a good or a bad thing is a quasi-religious issue • Cons: may cause silent failures difficult to track down • Pros: allows flexibility 20
  • 24. A touch of Class • Classes are generally divided into two chunks of code @interface MyClass defined in @end MyClass.h @implementation MyClass defined in @end MyClass.m 21
  • 25. Inheritance • The @interface declaration allows to specify a parent class @interface MyClass : NSObject • NSObject is the Cocoa- base class- but it is (actually another one exists NSProxy not of our interest) 22
  • 26. Methods declaration • Methods are declared as follows @interface MyClass : NSObject + (MyClass *)myClassInstance; - (NSString *)sayHelloClass; @end • Class methods starts with the + sign • Instance methods with the - sign 23
  • 27. Methods definition • Methods are then defined in the @implementation section of the class @implementation MyClass - (NSString *)sayHelloClass { return @”Hello Class!”; } ... @end 24
  • 28. Instance variables • Instance vars are traditionally declared in the @interface section. • However since iOS 5 it is allowed to declare them in the @implementation • Consider that the @interface section is usually visible to other classes 25
  • 29. Instance variables • Here’s an example of ivars declaration @interface MyClass : NSObject { NSInteger anInteger; NSString * aString; } @end 26
  • 30. Properties • A property is a syntactical feature of Obj-C 2.0, i.e. syntactic sugar for calling an accessor method. Example: NSString * name = [aPerson name]; [aPerson setName:@”Mary”]; equivalent to NSString * name = aPerson.name; aPerson.name = @”Mary”; 27
  • 31. Properties declaration • A property is generally declared in the @interface section as follows (< iOS4 style) @property(nonatomic, retain)this changed * NSString * since iOS5 name; • The above line declares the accessor methods for the name variable. • The options in the parenthesis define the 28
  • 32. Properties definition • The actual implementation of accessor methods is achieved like follows: @implementation MyClass @synthesize name; ... • The @synthesize keyword provides the implementation of the two methods - (NSString *)name - (void)setName:(NSString *)aName 29
  • 35. Memory Management alloc retain count 1 30
  • 36. Memory Management alloc retain count I care! 1 2 30
  • 37. Memory Management alloc retain count I care! 1 2 I care! I care! 5 I care! 30
  • 38. Memory Management alloc retain count I care! 1 2 I care! I don’t care any longer I care! me neither 1 5 I care! neither do I neither do I 30
  • 39. Memory Management alloc retain count I care! 1 2 I care! I don’t care any longer I care! me neither 1 5 I care! neither do I neither do I I don’t care... 0 30
  • 40. Memory Management alloc retain count I care! 1 2 I care! I don’t care any longer I care! me neither 1 5 I care! neither do I neither do I I don’t care... dealloc 0 30
  • 41. The NARC Rule • Every new, alloc, retain, copy (and mutableCopy) call MUST be balanced with a release • This still holds even under ARC (Automatic Retain Count). The only difference is that the rule is automatically respected by the compiler for you. 31
  • 42. Accessor methods and memory management - (void)setName:(NSString *)newName { if (newName != self->name) { /* release the old object*/ [self->name release]; /* retain the new one */ self->name = [newName retain]; } } 32
  • 43. Memory policies • strong/retain: ‘normal’ reference that increases the retainCount • copy: same as retain, but clones the object • weak: ARC specific. Does not retain the object. Automatically nullify the pointer • assign: pre-ARC. Same as weak but dåoes not automatically nullify the pointer! 33
  • 44. Other options • nonatomic/atomic: thread-safe or not. Default is atomic. • getter/setter: defines the getter/setter names • readonly/readwrite: whether produce the setter or not. Default is readwrite. 34
  • 45. References • Programming iOS 5 by Matt Neuborg • Apple official documentation 35
  • 46. Demo
  • 47. Demo

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n