Objective-C OOP Spring 2003. OOP Conceptually the same as C++, Java, and all other object oriented languages The syntax, however… …is, well, different.

Slides:



Advertisements
Similar presentations
Based on examples in "Programming in Objective-C," Copyright © 2004 by Sams Publishing O BJECTIVE -C Q UICK & D IRTY.
Advertisements

Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
C++ fundamentals.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
CSSE501 Object-Oriented Development. Chapter 5: Messages, Instances and Initialization  This chapter examines OOP run-time features: Object Creation.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Refactoring Moving a console app to a UI app. Refactoring Goal: change a console app to a UI app Principles: The main.m goes away The local variables.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
More on Classes Inheritance Copyright © 2012 by Yong-Gu Lee
Introduction to Objective-C and Xcode (Part 2) FA 175 Intro to Mobile App Development.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
The Java Programming Language
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Objective-C1 CS151 Presentation: Objective C Kai Tai Pang William Sze.
Learners Support Publications Classes and Objects.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Everything Is an Object Manipulate objects with references The identifier you manipulate is actually a “reference” to an object. Like a television.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Passing data between storyboard views Singleton pattern.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Introduction to Generics
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Polymorphism, Dynamic Typing, and Dynamic Binding Copyright © 2012 by Yong-Gu Lee
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
OOP with Objective-C Categories, Protocols and Declared Properties.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Polymorphism, Virtual Methods and Interfaces Version 1.1.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Design issues for Object-Oriented Languages
User-Written Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Object Oriented Programming in java
Java Programming Language
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Objective-C OOP Spring 2003

OOP Conceptually the same as C++, Java, and all other object oriented languages The syntax, however… …is, well, different Apple’s documentation on Objective-C classes: ammingWithObjectiveC/DefiningClasses/DefiningClasses.html ammingWithObjectiveC/DefiningClasses/DefiningClasses.html

OOP Examples in these slides are available as a compressed Xcode project (intro_classes.xcodeproj) at:

Methods & Messages Methods of class instances are called by passing messages The syntax is square brackets The instance is the first item in the backets The message or method name is the second item #import #import "alien.h" int main(int argc, const char * argv[]) { alien *george; double timeToHome; george = [[alien alloc] init]; timeToHome = [george calcTimeToHome]; // continued on next slide Variable holding object Method being called (note: no parameters) All variables that hold objects must be pointers Brackets around the call If you try to use a static variable to hold an object will get the error “interface type cannot be statically allocated”

Methods & Messages The syntax is square brackets The instance is the first item in the backets The message or method name is the second item The argument is the third item #import #import "alien.h" int main(int argc, const char * argv[]) { alien *george; double timeToHome; double timeToPlace; george = [[alien alloc] init]; timeToPlace =[george timeToPlace: 22000]; // continued on next slide Variable holding object Method being called (note: 1 parameter) Argument If you try to use a static variable to hold an object will get the error “interface type cannot be statically allocated”

Methods & Messages The syntax is square brackets The instance is the first item in the backets The message or method name is the second item followed by a colon The first argument is the third item The next part of the method name is the fourth item followed by colon #import #import "alien.h" int main(int argc, const char * argv[]) { alien *george; double timeToHome; double timeToPlace; george = [[alien alloc] init]; timeToPlace =[george timeWithSpeed: atDistance: ]; // continued on next slide Variable holding object Method being called (note: 2 parameters) First argument Second argument

Properties Changing properties Setters and getters are created automatically by directive Two ways of using setters and getters: brackets and dot- notation #import #import "alien.h" int main(int argc, const char * argv[]) { alien *george; double timeToHome = 0.0; george = [[alien alloc] init]; george.planet george.numEyes = 8; george.distanceToHome = 10000; // light years george.speedSpaceShip = 10.4; // hours/light year } return 0; } Normal bracket notation Dot notation It’s good to initialize variables when you declare them. This isn’t necessary for object pointers, because the compiler will automatically set the variable to nil if you don’t specify any other initial value:

Creating Classes Interface and implementation are separate (like C++) Can put both in same file Or in separate.h and.m files Interface (.h file): alien : NSObject { //properties double distanceToHome; } // methods - (double) Even console applications use the Foundation framesworks The interface starts The interface ends All classes inherit from NSObject Indicate inheritance with colon : NSObject Methods starting with a dash are instance methods Methods starting with a plus sign are class methods Return type

Implementation file Implementation file (.m file): #import numEyes, planet, distanceToHome, speedSpaceShip; - (double) calcTimeToHome { double theTime; theTime = distanceToHome / speedSpaceShip; return theTime; Must import the.h file The implementation starts nameOfClass The implementation ends Use directive to create setters and getters automatically (see later slide) Signature is the same as in the interface file. Return value

Method with a parameter Implementation file (.m file): #import numEyes, planet, distanceToHome, speedSpaceShip; - (double) timeToPlace: (double) dist { double theTime = dist / speedSpaceShip; return theTime; Each argument must have a selector and a formal parameter Signature is the same as in the interface file. Return value

Method with two parameters Implementation file (.m file): #import numEyes, planet, distanceToHome, speedSpaceShip; - (double) timeWithSpeed: (double) theSpeed atDistance: (double) theDist { double theTime = theDist / theSpeed; return theTime; Each argument must have a selector and a formal parameter Signature is the same as in the interface file. Return value

init method Implementation file (.m file): #import numEyes, planet, distanceToHome, speedSpaceShip; - (id) init { if (self = [super init]) { numEyes = 4; planet distanceToHome = ; speedSpaceShip = 1000; return (self); } return nil; First call the init of the superclass. It may return a new instance of you and it may fail (in that case it returns nil and the if statement fails) Signature is the same as in the interface file. Must return self or nil for george = [[alien alloc] init] to work. In objective-C self is a built-in variable that allows code to refer to itself.

init method with parameters #import numEyes, planet, distanceToHome, speedSpaceShip; - (id) initWithNum: (int) a andDistance: (double) b andPlanet: (NSString *) c { if (self = [super init]) { numEyes = 4; planet = c; distanceToHome = b; speedSpaceShip = a; return (self); } return nil; Use directive to create setters and getters automatically (see next slide) Signature is the same as in the interface file. First call the init of the superclass. It may return a new instance of you and it may fail (in that case it returns nil and the if statement fails) Must return self or nil for george = [[alien alloc] initWithNum: 4 andDistnce: 22000] to work. Xcode 4.5: To return “self” the method name must begin with “initWith” where only the ‘W’ is capitalized.

@synthesize In Xcode 4.5, statement in the.m file is now optional, and properties are synthesized automatically. Automatically generated IBOutlet properties therefore no longer because it's no longer required. When properties are synthesized automatically (without an statement) the corresponding instance variable is prepended with an underscore. This is so the instance variable and property names don't overlap. Accessing instance variables and properties has not changed. All that has changed is the default name of the instance variable. E.g.: _foo // Setting an instance variable directly. self.foo // Setting an instance variable via a property accessor method. The underscore is merely a matter of style, so that it's more clear that you're accessing the instance variable rather than the property. You can add statement yourself, and that will force the name of the corresponding instance variable to be whatever you want it to be. Likewise, if you add your own property accessor methods then that will prevent the instance variable from being generated automatically.

@synthesize Example of the use of properties: [george george.numEyes = 8; george.distanceToHome = 10000; // light years george.speedSpaceShip = 10.4; theSpeed = [george speedSpaceShip]; theDistance = george.distanceToHome; speed is %.2f and his distance to home is %.2f\n", theSpeed, automatically gives a setter: [object setVariableName: value] Where “set” is lowercase, variable name is same as property except first letter is always capitalized Or: can use the dot notation. Do not change variable automatically gives a getter: [object variableName] Where “variable name is same as Or: can use the dot notation. Do not change variable name.

description method The description method. Override the method from the superclass. Do not have to declare in the interface. #import numEyes, planet, distanceToHome, speedSpaceShip; - (NSString *) description { NSString *aboutMe; aboutMe = [NSString am an alien that lives on with %d eyes!", planet, numEyes ]; return aboutMe;} // description This method is not in the.h file. It is called when you print an instance of this class. The method is used to allow a class to print out a string describing itself. stringWithFormat is a class method. So we don’t use a variable as the first object, but the name of the class. Note that this particular method ( stringWithFormat ) works like printf instead of like normal methods!

description method The description method. Override the method from the superclass. Do not have to declare in the interface. #import numEyes, planet, distanceToHome, speedSpaceShip; sally = [alien new]; the description: you can use new if there are no arguments to the constructor; this does both alloc and init

Arrays of objects To put objects in arrays use the id class #import numEyes, planet, distanceToHome, speedSpaceShip; id theAliens[5]; // automatically an array of pointers // insert code to create two aliens in variables george and sally theAliens[0] = george; // automatically stores address theAliens[1] = sally; george's description: From Apple’s documentation: As mentioned earlier, you need to use a pointer to keep track of an object in memory. Because of Objective-C’s dynamic nature, it doesn’t matter what specific class type you use for that pointer—the correct method will always be called on the relevant object when you send it a message. The id type defines a generic object pointer. It’s possible to use id when declaring a variable, but you lose compile-time information about the object. id is Objective-C’s root object (it’s a NSObject ).

Determining Variable type To determine the type of a variable holding a class, use class methods from the NSObject class if ([george isKindOfClass:[alien class]]) is an alien"); else is NOT an alien (despite what you think)"); is of type [alien class]); The class nameThe variable that holds an instance of a class. The class method returns a NSString

Pass-by-reference Common technique in many languages Example: void f(int &x) { x = 55; } int main(int argc, char*argv[]) { int x = 42; f(y); printf(“y = %d\n”, y); // prints 55 } Does not exist in Objective-C, even if you’re using a pure C function in the.m file!

Virtual methods (not) The term "virtual function" has no direct counterpart in Objective-C. In Objective-C you don't call functions on objects, you send messages to them. The object itself then decides how to respond to the message, typically by looking up the message in its class object, finding the associated method and invoking it. This all happens at run time, not compile time. The mapping between messages ("selectors" is the technical term) and methods is built entirely from The method declarations in are only there to give the compiler the information it needs to warn you that you may have forgotten a method implementation. And it is only a warning because you can't tell until run time whether whether the object really does respond to the message or not. For example, somebody else could add a category to an existing class that provides implementations for missing methods, or a class could override forwardingTargetForSelector: to forward messages it doesn't respond to elsewhere. This is from JeremyP on stackOverflow: function-in-objective-c Not clear this is true for the most recent version of Objective-C

C++ vs Objective C Virtual vs ?? Abstract vs protocol ?? Vs categories