Objective-C slides

download Objective-C slides

of 46

Transcript of Objective-C slides

  • 7/27/2019 Objective-C slides

    1/46

    Vitor Carreira

    ESTG/IPLJuly 24-28, 2012

    Leiria, Portugal

    Objective-CDay 1 - Session 1

  • 7/27/2019 Objective-C slides

    2/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Quick Introduction

    2

  • 7/27/2019 Objective-C slides

    3/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Requirements

    Requirements for this session

    Moderate knowledge of the C programminglanguage

    Basic knowledge of Object OrientedProgramming concepts (instance vs class,encapsulation, inheritance and polymorphism)

    3

  • 7/27/2019 Objective-C slides

    4/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Why Objective-C?

    Selected as the main language by NeXT(company founded by Steve Jobs) to develop

    the NeXTStep OS In 1996, Apple acquires NeXT and starts

    developing Mac OS X (2001) usingObjective-C

    Objective-C is not a choice but rather alegacy :)

    4

  • 7/27/2019 Objective-C slides

    5/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Syntax

    Objective-C 2.0 is a superset of the C99 standard. All features of the Clanguage are preserved

    Case sensitive, strongly typed, every variable should be declared beforeused, separates function declaration (header file) from function

    implementation (implementation file), vars declared inside a functionare local, pass by reference using pointers, etc

    Same set of operators and control flow structures New features

    Extensions to the C language are identified with the @ symbol

    New file extensions: .m (implementation file), .h (header file) Var names: lowerCamelCase Function names: UpperCamelCase

    5

  • 7/27/2019 Objective-C slides

    6/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Data value types

    Value types: char, int, float, double

    Modifiers: unsigned, short, long By default, are integers are signed

    Enumerations: keyword enum

    Structures: keyword struct

    6

  • 7/27/2019 Objective-C slides

    7/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Pre-processor

    All lines that start with # are executed by the pre-processor. Justto recap:

    #define - defines a macro

    #if, #else, #endif - conditional includes code or macros #import - includes the file only once (should be used instead

    of #include)

    7

  • 7/27/2019 Objective-C slides

    8/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Hello World

    8

    main.m

  • 7/27/2019 Objective-C slides

    9/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Demo timeLets tr it on Xcode

    9

  • 7/27/2019 Objective-C slides

    10/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Classes

    10

  • 7/27/2019 Objective-C slides

    11/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Classes 1/2

    11

    In Objective-C, a class has two parts:

    @interface - part where the class interface isdeclared (public instance/class methods andpublic properties). The public interface must beplaced on an header file (.h)

    @implementation - part where the methods areimplemented. The implementation must beplaced on a code file (.m)

  • 7/27/2019 Objective-C slides

    12/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Classes 2/2

    Some conventions: Class name: UpperCamelCase

    Members and properties: lowerCamelCase Objective-C doesnt have namespaces. It is

    recommended to use a prefix of 2 to 4 letters

    to avoid collisions between class names Some prefixes are already reserved: NS, IB,

    CG, etc

    12

  • 7/27/2019 Objective-C slides

    13/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Interface part 1/3

    13

    Example (ComplexNumber.h)

    Syntax

  • 7/27/2019 Objective-C slides

    14/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Interface part 2/3

    14

    Every class should be a direct or indirectdescendant ofNSObject

    Instance variables (ivars) that are protected orpublic (not recommended) are declared between {} If no scope is given, ivars are @protected.

    Available scopes: @public, @protected,

    @private and @package

    Syntax to declare an instance variable:Type instanceVarName;

  • 7/27/2019 Objective-C slides

    15/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Interface part 3/3

    15

    Method declaration:MethodType (ReturnType)namePart1: (Type)param1

    namePart2: (Type)param2, ...;

    Method type: Use the - sign for instance methods

    Use the + sign for class methods

  • 7/27/2019 Objective-C slides

    16/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Method overloading

    Method overloading is not supported Methods with the same name but different

    parameter types

    How the name of the method is represented?

    16

    // Name = modulus- (double)modulus;

    // Name = debug- (void)debug;

    // Name = setRadius:phase:- (void)setRadius:(double)aRadius phase:(double)aPhase;

    // Name = setRadius:- (void)setRadius:(double)aRadius

  • 7/27/2019 Objective-C slides

    17/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Syntax

    Implementation part 1/2

    17

  • 7/27/2019 Objective-C slides

    18/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Example (ComplexNumber.m)

    Implementation part 2/2

    18

  • 7/27/2019 Objective-C slides

    19/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Putting all together

    19

    [[ComplexNumber alloc] init] Allocates e initializes a new instance of ComplexNumber An object is always represented by a pointer

    main.m

  • 7/27/2019 Objective-C slides

    20/46

  • 7/27/2019 Objective-C slides

    21/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Getters and setters 1/3

    By convention:

    The getter method name is equal to the ivar.Theget prefix is not used

    The setter has the following name:- (void)set:(IVarType)value

    21

  • 7/27/2019 Objective-C slides

    22/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Getters and setters 2/3

    22

  • 7/27/2019 Objective-C slides

    23/46

  • 7/27/2019 Objective-C slides

    24/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Properties 1/4

    24

    Objective-C 2.0 has introduced a new syntax to implementgetters and setters called dot syntax

    Invoking getters and setters becomes familiar. Some examples:

    int age = [person age];

    int age = person.age; // getter dot syntax

    [person setAge: 39];

    person.age = 39;// setter dot syntax

    [[person father] setAge: 68];

    person.father.age = 68; // setter dot syntax

  • 7/27/2019 Objective-C slides

    25/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Properties 2/4

    25

    Declaring a property: On the interface part use the @propertydirective

    @property (optional attributes) PropertyType propertyName

  • 7/27/2019 Objective-C slides

    26/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Properties 3/4

    26

    Synthesizing a property: On the implementation part use the @synthesize directive

    @synthesize propertyName[=optional_ivarname];

    By default, @synthesize follows the same conventions forgetters and setters and injects the following pair ofmethods:-(void)setIVarName:(Type)value;

    -(Type)varIName;

  • 7/27/2019 Objective-C slides

    27/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Properties 4/4

    27

    Easier to type. Easierto remember

  • 7/27/2019 Objective-C slides

    28/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Inheritance 1/2

    28

    Objective-C only supports single inheritance There is no such thing as a protected method

    To redefine a parent method you just have toprovide the new implementation (keeping themethod signature)

    The keyword selfis a reference for the currentinstance

    The keyword super refers to the parent of thecurrent instance

  • 7/27/2019 Objective-C slides

    29/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Inheritance 2/2

    In Objective-C method invocation follows the dynamicbinding mechanism. One a message is sent to a receptor:

    The runtime checks if the receptor implements the methodinvoked. If the method is founded it is executed.

    If the method is not founded, the message is sent to thereceptors parent

    The receptor hierarchy is traversed until one of thefollowing conditions is verified:

    The method is founded and invoked The method is not found when reaching the hierarchy top and an

    exception is thrown

    29

  • 7/27/2019 Objective-C slides

    30/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Some LanguageConsiderations

    30

  • 7/27/2019 Objective-C slides

    31/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Exceptions 1/3

    Exception handling is similar to C# or Java

    31

    @try {[f noSuchMethod];

    }@catch (NSException *exception) {

    NSLog(@Caught %@%@, [exception name], [exception reason]);}@finally {

    NSLog(@Always called);

    }

  • 7/27/2019 Objective-C slides

    32/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Exceptions 2/3

    You can have multiple @catch blocks to catchdifferent types of exceptions

    Use @throw to throw an exception

    If inside a @catch block the exception instance can beomitted@throw; // Re throws the exception caught

    NSException is the base class for all exceptions The runtime doesnt impose this kind of check

    32

  • 7/27/2019 Objective-C slides

    33/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Exceptions 3/3

    In languages like C# or Java, exceptions is fairly commonplaceand used intensively to signal errors that affect the executionflow

    Exceptions are resource-intensive in Objective-C. You shouldnot use exceptions for general flow-control, or simply tosignify errors. Instead you should use the return value of amethod or function to indicate that an error has occurred,and provide information about the problem in an error object

    33

    Veryimportant

  • 7/27/2019 Objective-C slides

    34/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    BOOL vs bool

    Objective-C 1.0 didnt have a boolean data type So the type BOOL was introduced to the language with

    the macros YES (true) and NO (false)

    Objective-C 2.0 is a superset of C99 so it also has theboolean type bool that is almost never used due thelegacy code

    34

    BOOL isLessonComplete = NO;bool newButSeldomUsed = true;

  • 7/27/2019 Objective-C slides

    35/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Static vs dynamic typing

    Static typing - the data type is alwaysspecified

    ComplexNumber *aNumber;

    Dynamic typing - the data type is notspecified. So the variable can represent any

    object (equivalent to the void * in C)id anyObject;

    35

  • 7/27/2019 Objective-C slides

    36/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Nil instance

    The keyword nil represents a null instance. It can be used: To assign an null object to a variable

    aComplexNumber = nil;

    As part of a conditionif (aComplexNumber == nil) or if (!aComplexNumber)

    As a method argument:[slider setTarget: nil];

    As a receptor (message is ignored and returns 0)aComplexNumber = nil;

    value = [aComplexNumber modulus];

    36

  • 7/27/2019 Objective-C slides

    37/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Selectors 1/2

    SEL is a data type called selector thatrepresents a method (similar to a functionpointer)

    A selector is declared using the methods fullname. The following method- (void)setRadius:(double)r phase:(double)p

    Could be represented with the followingselector:SEL setAll = @selector(setRadius:phase:);

    37

  • 7/27/2019 Objective-C slides

    38/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Selectors 2/2

    38

    The NSObject class provides several methodsthat work with selectors (e.g.respondsToSelector, performSelector, etc). For

    example:

    id receiver = self.target;

    SEL sel = self.action;

    if ([receiver respondsToSelector:sel]) {

    [receiver performSelector:sel withObject:self];

    }

  • 7/27/2019 Objective-C slides

    39/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation andInitialization

    39

    There is no such thing asconstructors

  • 7/27/2019 Objective-C slides

    40/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation and

    initialization 1/5

    40

    Two steps are required to instantiate an class:

    1. Allocate memory for the instance.NSObject provides twomethods for that: alloc e allocWithZone

    When memory is allocated all ivars are set to zero (objects are set to nil)

    2. Initialize the instance with the desired values. The class isresponsible to provide proper initializers to initialize the instance.

    By convention (this is very important) all initializers methods muststart with init

    All classes that have instance variables should provide at least oneinitializer

    AClass *anObject = [[AClass alloc] init];

  • 7/27/2019 Objective-C slides

    41/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation and

    initialization 2/5

    41

    An initializer must initialize all ivars of thereceptor and returns its own instance

    Exceptionally a different instance or even nil canbe returned by an initializer. So the valuereturned by the initializer should always be kept

    By convention, the initializer should be called onlyonce (very important for memory management)

    -(id)init {...}

  • 7/27/2019 Objective-C slides

    42/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation and

    initialization 2/5

    42

    AClass *anObject = [AClass alloc];[anObject init];[anObject someMethod];

    AClass *anObject = [AClass alloc];anObject = [anObject init];[anObject someMethod];

    Incorrect Correct

    AClass *anObject = [[AClass alloc] init];[anObject someMethod];

    Typical code

  • 7/27/2019 Objective-C slides

    43/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation and

    initialization 4/5

    43

    Rules to implement an initializer By convention, the method should start with the name init The method must return id

    If the class has more than one initializer it is required to state whichone is the designated initializer. This is the initializer that all the otherinitializers should invoke

    The designated initializer is the only one to invoke the parent initializer You must assign to self the result of calling the designated or parent

    initializer. You should check if the result is nil (exceptionally an initializercan return nil or an different instance of the one currently allocated)

    You should not use getters and setters to initialize ivars The initializer must always return self (or nil if an error occurs)

  • 7/27/2019 Objective-C slides

    44/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Allocation and

    initialization 5/5

    44

    Example

  • 7/27/2019 Objective-C slides

    45/46

    July 24-28, 2012 iOS Game Development - International Summer School, ESTG/IPL

    Combining allocation

    and initialization Some classes combine allocation and

    initialization in a single step

    This methods are called convenienceconstructors and usually start with the nameof the class

    Examples from NSString:

    45

    + (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;+ (id)stringWithFormat:(NSString *)format, ...;

  • 7/27/2019 Objective-C slides

    46/46

    Before moving to the next session.Any questions?