SlideShare ist ein Scribd-Unternehmen logo
1 von 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
  inx 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 Inx 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 Inx 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 Inx 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 Inx 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               dened in
  @end                             MyClass.h
  @implementation MyClass dened 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 denition
• 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 denition
• 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

Weitere ähnliche Inhalte

Was ist angesagt?

みゆっき☆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 Language
CodeFest
 

Was ist angesagt? (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
 

Andere mochten auch

Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Mayank Jalotra
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
Ashiq Uz Zoha
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Sunny Shaikh
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof language
nicky_walters
 
I Phone Development Presentation
I Phone Development PresentationI Phone Development Presentation
I Phone Development Presentation
Aessam
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
sagaroceanic11
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
Haitham El-Ghareeb
 

Andere mochten auch (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
 

Ähnlich wie 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-C
DataArt
 
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 study
DefconRussia
 
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
Bill Buchan
 
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
 

Ähnlich wie 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
 

KĂźrzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

KĂźrzlich hochgeladen (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 

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 inx 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 Inx 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 Inx 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 Inx 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 Inx 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 difcult to track down • Pros: allows flexibility 20
  • 24. A touch of Class • Classes are generally divided into two chunks of code @interface MyClass dened in @end MyClass.h @implementation MyClass dened 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 denition • Methods are then dened 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 dene the 28
  • 32. Properties denition • 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 specic. 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: denes 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 ofcial documentation 35
  • 46. Demo
  • 47. Demo

Hinweis der Redaktion

  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