SlideShare a Scribd company logo
INTRODUCTION TO
OBJECTIVE-C
COMPILED BY: ASIM RAIS SIDDIQUI
Goals of the Lecture

    Present an introduction to Objective-C 2.0
    Coverage of the language will be INCOMPLETE
        We’ll see the basics… there is a lot more to learn
    There is a nice Objective-C tutorial located here:
     http://cocoadevcentral.com/d/learn_objectivec
History (I)
  Brad Cox created Objective-C in the early 1980s
     It was his attempt to add object-oriented programming
     concepts to the C programming language
     NeXT Computer licensed the language in 1988; it was
     used to develop the NeXTSTEP operating system,
     programming libraries and applications for NeXT
     In 1993, NeXT worked with Sun to create OpenStep,
     an open specification of NeXTSTEP on Sun hardware
History (II)
  In 1997,Apple purchased NeXT and transformed
  NeXTSTEP into MacOS X which was first released in the
  summer of 2000
    Objective-C has been one of the primary ways to
    develop applications for MacOS for the past 11 years
    In 2008, it became the primary way to develop
    applications for iOS targeting (currently) the iPhone
    and the iPad and (soon, I’m guessing) the AppleTV
Objective-C is“C plus Objects” (I)
  Objective-C makes a small set of extensions to C which
  turn it into an object-oriented language
  It is used with two object-oriented frameworks
     The Foundation framework contains classes for basic
     concepts such as strings, arrays and other data
     structures and provides classes to interact with the
     underlying operating system
     The AppKit contains classes for developing applications
     and for creating windows, buttons and other widgets
Objective-C is“C plus Objects” (II)
  Together, Foundation and AppKit are called Cocoa
  On iOS,AppKit is replaced by UIKit
     Foundation and UIKit are called Cocoa Touch
  In this lecture, we focus on the Objective-C language,
     we’ll see a few examples of the Foundation framework
     we’ll see examples of UIKit in Lecture 13
C Skills? Highly relevant
  Since Objective-C is“C plus objects” any skills you have in
  the C language directly apply
     statements, data types, structs, functions, etc.
  What the OO additions do, is reduce your need on
     structs, malloc, dealloc and the like
     and enable all of the object-oriented concepts we’ve
     been discussing
  Objective-C and C code otherwise freely intermix
DevelopmentTools (I)
  Apple’s XCode is used to develop in Objective-C
     Behind the scenes, XCode makes use of either gcc or
     Apple’s own LLVM to compile Objective-C programs
  The latest version of Xcode, Xcode 4, has integrated
  functionality that previously existed in a separate
  application, known as Interface Builder
     We’ll see examples of that integration next week
DevelopmentTools (II)
  XCode is available on the Mac App Store
     It is free for users of OS X Lion
     Otherwise, I believe it costs $5 for previous versions of
     OS X
  Clicking Install in the App Store downloads a program
  called“Install XCode”.You then run that program to get
  XCode installed
HelloWorld
  As is traditional, let’s look at our first objective-c program
  via the traditional HelloWorld example
  To create it, we launch XCode and create a New Project
Introduction to Objective - C
Introduction to Objective - C
Similar to what we saw
with Eclipse, XCode
creates a default project
for us;

There are folders for this
program’s source code (.m
and .h files), frameworks,
and products (the application itself)

Note: the Foundation
framework is front and
center and HelloWorld is
shown in red because it
hasn’t been created yet
The resulting project structure on disk does not map completely to what is shown in Xcode; The source file, man page, and pre-
compiled header file are all stored in a sub-directory of the main directory.


The project file HelloWorld.xcodeproj is stored in the main directory. It is the file that keeps track of all project settings and the

location of project files.


XCode project directories are a lot simpler now that files generated during a build are stored elsewhere.
Where is the actual application?
  After you ran the application, HelloWorld switched from
  being displayed in red to being displayed in black
     You can right click on HelloWorld and select“Show in
     Finder” to see where XCode placed the actual
     executable
  By default, XCode creates a directory for your project in
     ~/Library/Developer/XCode/DerivedData
  For HelloWorld, XCode generated 20 directories
  containing 31 files!
Objective-C programs start with a function called main, just like C programs; #import is
similar to C’s #include except it ensures that header files are only included once and only
once. Ignore the “NSAutoreleasePool” stuff for now
Thus our program calls a function, NSLog, and returns 0

The blue arrow indicates that a breakpoint has been set; gdb
will stop execution on line 7 the next time we run the program
Objective-C classes
  Classes in Objective-C are defined in two files
     A header file which defines the attributes and method
     signatures of the class
     An implementation file (.m) that provides the method
     bodies
Header Files
     The header file of an Objective-C class traditionally has
     the following structure
 <import statements>

 @interface <classname> : <superclass name> {

      <attribute definitions>

 }

 <method signature definitions>

 @end
Header Files
  With Objective-C 2.0, the structure has changed to the
  following (the previous structure is still supported)
 <import statements>

 @interface <classname> : <superclass name>

 <property definitions>

 <method signature definitions>

 @end
Introduction to Objective - C
What’s the difference?
  In Objective-C 2.0, the need for defining the attributes of a
  class has been greatly reduced due to the addition of
  properties
     When you declare a property, you automatically get
        an attribute (instance variable)
        a getter method
        and a setter method
     synthesized (automatically added) for you
New Style
  In this class, I’ll be using the new style promoted by
  Objective-C 2.0
     Occasionally we may run into code that uses the old
     style, I’ll explain the old style when we encounter it
Objective-C additions to C (I)
  Besides the very useful #import, the best way to spot an
  addition to C by Objective-C is the presence of this symbol
Objective-C additions to C (II)
  In header files, the two key additions from Objective-C are
     @interface
  and
     @end
  @interface is used to define a new objective-c class
     As we saw, you provide the class name and its superclass;
     Objective-C is a single inheritance language
  @end does what it says, ending the @interface compiler directive
Introduction to Objective - C
We’ve added one property: It’s called greetingText. Its type is
NSString* which means “pointer to an instance of NSString”

We’ve also added one method called greet. It takes no
parameters and its return type is “void”.

(By the way, NS stands for “NeXTSTEP”! NeXT lives on!)
Objective-C Properties (I)
 An Objective-C property helps to define the public interface
 of an Objective-C class
        It defines an instance variable, a getter and a setter all
        in one go
 @property (nonatomic, copy) NSString* greetingText
 “nonatomic” tells the runtime that this property will never be
 accessed by more than one thread (use“atomic” otherwise)
 “copy” is related to memory management and will be
 discussed later
Objective-C Properties (III)
 @property (nonatomic, copy) NSString* greetingText
 If you have an instance of Greeter
        Greeter* ken = [[Greeter alloc] init];
 You can assign the property using dot notation
        ken.greetingText = @“Say Hello, Ken”;
 You can retrieve the property also using dot notation
        NSString* whatsTheGreeting = ken.greetingText;
Objective-C Properties (IV)
 Dot notation is simply“syntactic sugar” for calling the
 automatically generated getter and setter methods
        NSString* whatsTheGreeting = ken.greetingText;
 is equivalent to
        NSString* whatsTheGreeting = [ken greetingText];
 The above is a call to a method that is defined as
        - (NSString*) greetingText;
Objective-C Properties (V)
 Dot notation is simply“syntactic sugar” for calling the
 automatically generated getter and setter methods
        ken.greetingText = @“Say Hello, Ken”;
 is equivalent to
        [ken setGreetingText:@”Say Hello, Ken”];
 The above is a call to a method that is defined as
        - (void) setGreetingText:(NSString*) newText;
Objective-C Methods (I)
  It takes a while to get use to Object-C method signatures
 - (void) setGreetingText: (NSString*) newText;

  defines an instance method (-) called setGreetingText:
  The colon signifies that the method has one parameter
  and is PART OFTHE METHOD NAME
       newText of type (NSString*)
  The names setGreetingText: and setGreetingText refer to
  TWO different methods; the former has one parameter
Introduction to Objective - C
Let’s implement the method bodies
  The implementation file of a class looks like this
 <import statements>

 <optional class extension>

 @implementation <classname>

 <method body definitions>

 @end

 Let’s ignore the “optional class extension” part
 for now
But first, calling methods (I)
  The method invocation syntax of Objective-C is
     [object method:arg1 method:arg2 …];
  Method calls are enclosed by square brackets
     Inside the brackets, you list the object being called
     Then the method with any arguments for the methods
     parameters
But first, calling methods (II)
Here’s a call using Greeter’s setter method; @“Howdy!” is a shorthand
syntax for creating an NSString instance
   [greeter setGreetingText: @“Howdy!”];

Here’s a call to the same method where we get the greeting from
some other Greeter object
   [greeterOne setGreetingText:[greeterTwo greetingText]];

Above we nested one call inside another; now a call with multiple args
   [rectangle setStrokeColor: [NSColor red] andFillColor: [NSColor green]];
Memory Management (I)
  Memory management of Objective-C objects involves the
  use of six methods
     alloc, init, dealloc, retain, release, autorelease
  Objects are created using alloc and init
  We then keep track of who is using an object with retain
  and release
  We get rid of an object with dealloc (although, we never
  call dealloc ourselves)
Memory Management (II)
  When an object is created, its retain count is set to 1
     It is assumed that the creator is referencing the object
     that was just created
  If another object wants to reference it, it calls retain to
  increase the reference count by 1
     When it is done, it calls release to decrease the
     reference count by 1
  If an object’s reference count goes to zero, the runtime
  system automatically calls dealloc
Memory Management (III)
  I won’t talk about autorelease today, we’ll see it in action soon
  Objective-C 2.0 added a garbage collector to the language
     When garbage collection is turned on, retain, release, and
     autorelease become no-ops, doing nothing
     However, the garbage collector is not available when
     running on iOS, so the use of retain and release are still
     with us
  Apple recently released“automatic reference counting” which
  may make all of this go away (including the garbage collector)
Some things not (yet) discussed
  Objective-C has a few additions to C not yet discussed
     The type id: id is defined as a pointer to an object
        id iCanPointAtAString = @“Hello”;
        Note: no need for an asterisk in this case
     The keyword nil: nil is a pointer to no object
        It is similar to Java’s null
     The type BOOL: BOOL is a boolean type with valuesYES
     and NO; used throughout the Cocoa frameworks
Wrapping Up (I)
  Basic introduction to Objective-C
     main methods
     class and method definition and implementation
     method calling syntax
     creation of objects and memory management
  More to come as we use this knowledge to explore the
  iOS platform in future lectures
Primitive data types from C

    int, short, long


    float,double


    char
Classes from Apple

    NSString is a string of text that is immutable.
    NSMutableString is a string of text that is mutable.
    NSArray is an array of objects that is immutable.
    NSMutableArray is an array of objects that is mutable.
    NSNumber holds a numeric value.
Working with Objects & Messaging

   The majority of work in an
    Objective-C application happens
    as a result of messages being sent
    back and forth across an
    ecosystem of objects. Some of
    these objects are instances of
    classes provided by Cocoa or
    Cocoa Touch, some are
    instances of your own classes.
NSMutableString example
NSArray




   Initialize an NSArray by including a comma-separated list of objects
   between @[ and ]. The compiler converts that line of code into a call to
   the +[NSArray arrayWithObjects:count:] class method
NSDictionary
Dictionaries are very
common in iOS application
development.

A dictionary is nothing more
than a collection of key-
value pairs. The keys are
represented as strings and
the values are objects.

The keys in a dictionary must
be unique. As with other
collections, dictionaries have
two variants, mutable and
non-mutable.
Let’s look at a few examples. The code below creates a mutable dictionary and
adds a series of objects, including a string, a number and an array (with various
embedded object types):
NSNumber

    You can’t put scalar types like ints or floats directly into Foundation
     collections. You have to “box” them first by wrapping them in an
     NSNumber object.
NSNumber versus NSInteger

    NSInteger is nothing more than a synonym for a long integer.
    NSNumber is an Objective-C class, a subclass of NSValue to be
     specific. You can create an NSNumber object from a signed or
     unsigned char, short int, int, long int, long long int, float, double or
     BOOL.
    One of the primary distinctions is that you can use NSNumber in
     collections, such as NSArray, where an object is required. For
     example, if you need to add a float into an NSArray, you would first
     need to create an NSNumber object from the float:
Messages
   To get an object to do something, you send it a message
    telling it to apply a method. In Objective-C, message
    expressions are enclosed in square brackets
    [receiver message]
   The receiver is an object. The message is simply the name of a
    method and any arguments that are passed to it
Messages (cont.)

   For example, this message tells the myRect
    object to perform its display method, which
    causes the rectangle to display itself
    [myRect display];
    [myRect setOrigin:30.0 :50.0];
   The method setOrigin::, has two colons, one
    for each of its arguments. The arguments
    are inserted after the colons, breaking the
    name apart
Ad

More Related Content

What's hot (20)

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Java buzzwords
Java buzzwordsJava buzzwords
Java buzzwords
ramesh517
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Amit Soni (CTFL)
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
Youssef Mohammed Abohaty
 
C# Basics
C# BasicsC# Basics
C# Basics
Sunil OS
 
CSharp.ppt
CSharp.pptCSharp.ppt
CSharp.ppt
ckthesolo
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
Mindfire Solutions
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
Edureka!
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Object Oriented Programming ppt presentation
Object Oriented Programming ppt presentationObject Oriented Programming ppt presentation
Object Oriented Programming ppt presentation
AyanaRukasar
 
C# programming language
C# programming languageC# programming language
C# programming language
swarnapatil
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 
Packages in java
Packages in javaPackages in java
Packages in java
Jerlin Sundari
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
Aniruddha Chakrabarti
 
Java buzzwords
Java buzzwordsJava buzzwords
Java buzzwords
ramesh517
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Amit Soni (CTFL)
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
Edureka!
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Object Oriented Programming ppt presentation
Object Oriented Programming ppt presentationObject Oriented Programming ppt presentation
Object Oriented Programming ppt presentation
AyanaRukasar
 
C# programming language
C# programming languageC# programming language
C# programming language
swarnapatil
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 

Viewers also liked (19)

Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
Jussi Pohjolainen
 
Iphone programming: Objective c
Iphone programming: Objective cIphone programming: Objective c
Iphone programming: Objective c
Kenny Nguyen
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
Paolo Quadrani
 
50085245 final-project-of-lg-tv-2009-110919132403-phpapp01
50085245 final-project-of-lg-tv-2009-110919132403-phpapp0150085245 final-project-of-lg-tv-2009-110919132403-phpapp01
50085245 final-project-of-lg-tv-2009-110919132403-phpapp01
vinothp2k
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
Diksha Bhargava
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
Adam Musial-Bright
 
English ppt
English pptEnglish ppt
English ppt
culebro_007
 
English ppt 2
English ppt 2English ppt 2
English ppt 2
culebro_007
 
iOS 入門教學
iOS 入門教學iOS 入門教學
iOS 入門教學
Steven Shen
 
Haier presentation
Haier presentationHaier presentation
Haier presentation
Mohsin Zeb
 
Objektif pengajaran
Objektif pengajaranObjektif pengajaran
Objektif pengajaran
Sohib AlQuran
 
Smart TV
Smart TVSmart TV
Smart TV
Praveen Kumar
 
English literature ppt
English literature pptEnglish literature ppt
English literature ppt
lubi345
 
Java script ppt
Java script pptJava script ppt
Java script ppt
The Health and Social Care Information Centre
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Lg presentation (1)
Lg presentation (1)Lg presentation (1)
Lg presentation (1)
Amit Jha
 
Mba project report
Mba project reportMba project report
Mba project report
Cochin University
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Ad

Similar to Introduction to Objective - C (20)

Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
David Echeverria
 
Objective c
Objective cObjective c
Objective c
ricky_chatur2005
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
Danielle780357
 
Ios - Introduction to platform & SDK
Ios - Introduction to platform & SDKIos - Introduction to platform & SDK
Ios - Introduction to platform & SDK
Vibrant Technologies & Computers
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
georgebrock
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
bhargavi804095
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
bhargavi804095
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
Compare Infobase Limited
 
T2
T2T2
T2
lksoo
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
NicheTech Com. Solutions Pvt. Ltd.
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction
paramisoft
 
iOS course day 1
iOS course day 1iOS course day 1
iOS course day 1
Rich Allen
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
CoolGamer16
 
Getting started with code composer studio v4 for tms320 f2812
Getting started with code composer studio v4 for tms320 f2812Getting started with code composer studio v4 for tms320 f2812
Getting started with code composer studio v4 for tms320 f2812
Pantech ProLabs India Pvt Ltd
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
AnassElHousni
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
NEHARAJPUT239591
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
meharikiros2
 
Write native iPhone applications using Eclipse CDT
Write native iPhone applications using Eclipse CDTWrite native iPhone applications using Eclipse CDT
Write native iPhone applications using Eclipse CDT
Atit Patumvan
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
Javier Gonzalez-Sanchez
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
georgebrock
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
bhargavi804095
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
bhargavi804095
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
NicheTech Com. Solutions Pvt. Ltd.
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction
paramisoft
 
iOS course day 1
iOS course day 1iOS course day 1
iOS course day 1
Rich Allen
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
CoolGamer16
 
Getting started with code composer studio v4 for tms320 f2812
Getting started with code composer studio v4 for tms320 f2812Getting started with code composer studio v4 for tms320 f2812
Getting started with code composer studio v4 for tms320 f2812
Pantech ProLabs India Pvt Ltd
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
AnassElHousni
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
NEHARAJPUT239591
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
meharikiros2
 
Write native iPhone applications using Eclipse CDT
Write native iPhone applications using Eclipse CDTWrite native iPhone applications using Eclipse CDT
Write native iPhone applications using Eclipse CDT
Atit Patumvan
 
Ad

More from Asim Rais Siddiqui (8)

Understanding Blockchain Technology
Understanding Blockchain TechnologyUnderstanding Blockchain Technology
Understanding Blockchain Technology
Asim Rais Siddiqui
 
IoT Development - Opportunities and Challenges
IoT Development - Opportunities and ChallengesIoT Development - Opportunities and Challenges
IoT Development - Opportunities and Challenges
Asim Rais Siddiqui
 
iOS Memory Management
iOS Memory ManagementiOS Memory Management
iOS Memory Management
Asim Rais Siddiqui
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI Components
Asim Rais Siddiqui
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
Asim Rais Siddiqui
 
iOS Development (Part 1)
iOS Development (Part 1)iOS Development (Part 1)
iOS Development (Part 1)
Asim Rais Siddiqui
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS Development
Asim Rais Siddiqui
 
Understanding Blockchain Technology
Understanding Blockchain TechnologyUnderstanding Blockchain Technology
Understanding Blockchain Technology
Asim Rais Siddiqui
 
IoT Development - Opportunities and Challenges
IoT Development - Opportunities and ChallengesIoT Development - Opportunities and Challenges
IoT Development - Opportunities and Challenges
Asim Rais Siddiqui
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI Components
Asim Rais Siddiqui
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS Development
Asim Rais Siddiqui
 

Introduction to Objective - C

  • 2. Goals of the Lecture  Present an introduction to Objective-C 2.0  Coverage of the language will be INCOMPLETE  We’ll see the basics… there is a lot more to learn  There is a nice Objective-C tutorial located here:  http://cocoadevcentral.com/d/learn_objectivec
  • 3. History (I) Brad Cox created Objective-C in the early 1980s It was his attempt to add object-oriented programming concepts to the C programming language NeXT Computer licensed the language in 1988; it was used to develop the NeXTSTEP operating system, programming libraries and applications for NeXT In 1993, NeXT worked with Sun to create OpenStep, an open specification of NeXTSTEP on Sun hardware
  • 4. History (II) In 1997,Apple purchased NeXT and transformed NeXTSTEP into MacOS X which was first released in the summer of 2000 Objective-C has been one of the primary ways to develop applications for MacOS for the past 11 years In 2008, it became the primary way to develop applications for iOS targeting (currently) the iPhone and the iPad and (soon, I’m guessing) the AppleTV
  • 5. Objective-C is“C plus Objects” (I) Objective-C makes a small set of extensions to C which turn it into an object-oriented language It is used with two object-oriented frameworks The Foundation framework contains classes for basic concepts such as strings, arrays and other data structures and provides classes to interact with the underlying operating system The AppKit contains classes for developing applications and for creating windows, buttons and other widgets
  • 6. Objective-C is“C plus Objects” (II) Together, Foundation and AppKit are called Cocoa On iOS,AppKit is replaced by UIKit Foundation and UIKit are called Cocoa Touch In this lecture, we focus on the Objective-C language, we’ll see a few examples of the Foundation framework we’ll see examples of UIKit in Lecture 13
  • 7. C Skills? Highly relevant Since Objective-C is“C plus objects” any skills you have in the C language directly apply statements, data types, structs, functions, etc. What the OO additions do, is reduce your need on structs, malloc, dealloc and the like and enable all of the object-oriented concepts we’ve been discussing Objective-C and C code otherwise freely intermix
  • 8. DevelopmentTools (I) Apple’s XCode is used to develop in Objective-C Behind the scenes, XCode makes use of either gcc or Apple’s own LLVM to compile Objective-C programs The latest version of Xcode, Xcode 4, has integrated functionality that previously existed in a separate application, known as Interface Builder We’ll see examples of that integration next week
  • 9. DevelopmentTools (II) XCode is available on the Mac App Store It is free for users of OS X Lion Otherwise, I believe it costs $5 for previous versions of OS X Clicking Install in the App Store downloads a program called“Install XCode”.You then run that program to get XCode installed
  • 10. HelloWorld As is traditional, let’s look at our first objective-c program via the traditional HelloWorld example To create it, we launch XCode and create a New Project
  • 13. Similar to what we saw with Eclipse, XCode creates a default project for us; There are folders for this program’s source code (.m and .h files), frameworks, and products (the application itself) Note: the Foundation framework is front and center and HelloWorld is shown in red because it hasn’t been created yet
  • 14. The resulting project structure on disk does not map completely to what is shown in Xcode; The source file, man page, and pre- compiled header file are all stored in a sub-directory of the main directory. The project file HelloWorld.xcodeproj is stored in the main directory. It is the file that keeps track of all project settings and the location of project files. XCode project directories are a lot simpler now that files generated during a build are stored elsewhere.
  • 15. Where is the actual application? After you ran the application, HelloWorld switched from being displayed in red to being displayed in black You can right click on HelloWorld and select“Show in Finder” to see where XCode placed the actual executable By default, XCode creates a directory for your project in ~/Library/Developer/XCode/DerivedData For HelloWorld, XCode generated 20 directories containing 31 files!
  • 16. Objective-C programs start with a function called main, just like C programs; #import is similar to C’s #include except it ensures that header files are only included once and only once. Ignore the “NSAutoreleasePool” stuff for now Thus our program calls a function, NSLog, and returns 0 The blue arrow indicates that a breakpoint has been set; gdb will stop execution on line 7 the next time we run the program
  • 17. Objective-C classes Classes in Objective-C are defined in two files A header file which defines the attributes and method signatures of the class An implementation file (.m) that provides the method bodies
  • 18. Header Files The header file of an Objective-C class traditionally has the following structure <import statements> @interface <classname> : <superclass name> { <attribute definitions> } <method signature definitions> @end
  • 19. Header Files With Objective-C 2.0, the structure has changed to the following (the previous structure is still supported) <import statements> @interface <classname> : <superclass name> <property definitions> <method signature definitions> @end
  • 21. What’s the difference? In Objective-C 2.0, the need for defining the attributes of a class has been greatly reduced due to the addition of properties When you declare a property, you automatically get an attribute (instance variable) a getter method and a setter method synthesized (automatically added) for you
  • 22. New Style In this class, I’ll be using the new style promoted by Objective-C 2.0 Occasionally we may run into code that uses the old style, I’ll explain the old style when we encounter it
  • 23. Objective-C additions to C (I) Besides the very useful #import, the best way to spot an addition to C by Objective-C is the presence of this symbol
  • 24. Objective-C additions to C (II) In header files, the two key additions from Objective-C are @interface and @end @interface is used to define a new objective-c class As we saw, you provide the class name and its superclass; Objective-C is a single inheritance language @end does what it says, ending the @interface compiler directive
  • 26. We’ve added one property: It’s called greetingText. Its type is NSString* which means “pointer to an instance of NSString” We’ve also added one method called greet. It takes no parameters and its return type is “void”. (By the way, NS stands for “NeXTSTEP”! NeXT lives on!)
  • 27. Objective-C Properties (I) An Objective-C property helps to define the public interface of an Objective-C class It defines an instance variable, a getter and a setter all in one go @property (nonatomic, copy) NSString* greetingText “nonatomic” tells the runtime that this property will never be accessed by more than one thread (use“atomic” otherwise) “copy” is related to memory management and will be discussed later
  • 28. Objective-C Properties (III) @property (nonatomic, copy) NSString* greetingText If you have an instance of Greeter Greeter* ken = [[Greeter alloc] init]; You can assign the property using dot notation ken.greetingText = @“Say Hello, Ken”; You can retrieve the property also using dot notation NSString* whatsTheGreeting = ken.greetingText;
  • 29. Objective-C Properties (IV) Dot notation is simply“syntactic sugar” for calling the automatically generated getter and setter methods NSString* whatsTheGreeting = ken.greetingText; is equivalent to NSString* whatsTheGreeting = [ken greetingText]; The above is a call to a method that is defined as - (NSString*) greetingText;
  • 30. Objective-C Properties (V) Dot notation is simply“syntactic sugar” for calling the automatically generated getter and setter methods ken.greetingText = @“Say Hello, Ken”; is equivalent to [ken setGreetingText:@”Say Hello, Ken”]; The above is a call to a method that is defined as - (void) setGreetingText:(NSString*) newText;
  • 31. Objective-C Methods (I) It takes a while to get use to Object-C method signatures - (void) setGreetingText: (NSString*) newText; defines an instance method (-) called setGreetingText: The colon signifies that the method has one parameter and is PART OFTHE METHOD NAME newText of type (NSString*) The names setGreetingText: and setGreetingText refer to TWO different methods; the former has one parameter
  • 33. Let’s implement the method bodies The implementation file of a class looks like this <import statements> <optional class extension> @implementation <classname> <method body definitions> @end Let’s ignore the “optional class extension” part for now
  • 34. But first, calling methods (I) The method invocation syntax of Objective-C is [object method:arg1 method:arg2 …]; Method calls are enclosed by square brackets Inside the brackets, you list the object being called Then the method with any arguments for the methods parameters
  • 35. But first, calling methods (II) Here’s a call using Greeter’s setter method; @“Howdy!” is a shorthand syntax for creating an NSString instance [greeter setGreetingText: @“Howdy!”]; Here’s a call to the same method where we get the greeting from some other Greeter object [greeterOne setGreetingText:[greeterTwo greetingText]]; Above we nested one call inside another; now a call with multiple args [rectangle setStrokeColor: [NSColor red] andFillColor: [NSColor green]];
  • 36. Memory Management (I) Memory management of Objective-C objects involves the use of six methods alloc, init, dealloc, retain, release, autorelease Objects are created using alloc and init We then keep track of who is using an object with retain and release We get rid of an object with dealloc (although, we never call dealloc ourselves)
  • 37. Memory Management (II) When an object is created, its retain count is set to 1 It is assumed that the creator is referencing the object that was just created If another object wants to reference it, it calls retain to increase the reference count by 1 When it is done, it calls release to decrease the reference count by 1 If an object’s reference count goes to zero, the runtime system automatically calls dealloc
  • 38. Memory Management (III) I won’t talk about autorelease today, we’ll see it in action soon Objective-C 2.0 added a garbage collector to the language When garbage collection is turned on, retain, release, and autorelease become no-ops, doing nothing However, the garbage collector is not available when running on iOS, so the use of retain and release are still with us Apple recently released“automatic reference counting” which may make all of this go away (including the garbage collector)
  • 39. Some things not (yet) discussed Objective-C has a few additions to C not yet discussed The type id: id is defined as a pointer to an object id iCanPointAtAString = @“Hello”; Note: no need for an asterisk in this case The keyword nil: nil is a pointer to no object It is similar to Java’s null The type BOOL: BOOL is a boolean type with valuesYES and NO; used throughout the Cocoa frameworks
  • 40. Wrapping Up (I) Basic introduction to Objective-C main methods class and method definition and implementation method calling syntax creation of objects and memory management More to come as we use this knowledge to explore the iOS platform in future lectures
  • 41. Primitive data types from C  int, short, long  float,double  char
  • 42. Classes from Apple  NSString is a string of text that is immutable.  NSMutableString is a string of text that is mutable.  NSArray is an array of objects that is immutable.  NSMutableArray is an array of objects that is mutable.  NSNumber holds a numeric value.
  • 43. Working with Objects & Messaging  The majority of work in an Objective-C application happens as a result of messages being sent back and forth across an ecosystem of objects. Some of these objects are instances of classes provided by Cocoa or Cocoa Touch, some are instances of your own classes.
  • 45. NSArray Initialize an NSArray by including a comma-separated list of objects between @[ and ]. The compiler converts that line of code into a call to the +[NSArray arrayWithObjects:count:] class method
  • 46. NSDictionary Dictionaries are very common in iOS application development. A dictionary is nothing more than a collection of key- value pairs. The keys are represented as strings and the values are objects. The keys in a dictionary must be unique. As with other collections, dictionaries have two variants, mutable and non-mutable.
  • 47. Let’s look at a few examples. The code below creates a mutable dictionary and adds a series of objects, including a string, a number and an array (with various embedded object types):
  • 48. NSNumber  You can’t put scalar types like ints or floats directly into Foundation collections. You have to “box” them first by wrapping them in an NSNumber object.
  • 49. NSNumber versus NSInteger  NSInteger is nothing more than a synonym for a long integer.  NSNumber is an Objective-C class, a subclass of NSValue to be specific. You can create an NSNumber object from a signed or unsigned char, short int, int, long int, long long int, float, double or BOOL.  One of the primary distinctions is that you can use NSNumber in collections, such as NSArray, where an object is required. For example, if you need to add a float into an NSArray, you would first need to create an NSNumber object from the float:
  • 50. Messages  To get an object to do something, you send it a message telling it to apply a method. In Objective-C, message expressions are enclosed in square brackets [receiver message]  The receiver is an object. The message is simply the name of a method and any arguments that are passed to it
  • 51. Messages (cont.)  For example, this message tells the myRect object to perform its display method, which causes the rectangle to display itself [myRect display]; [myRect setOrigin:30.0 :50.0];  The method setOrigin::, has two colons, one for each of its arguments. The arguments are inserted after the colons, breaking the name apart