Introduction to iOS and Objective-C

Post on 25-May-2015

736 views 1 download

Tags:

description

A light introduction to iOS and Objective-C is given: - The iOS architecture - Objective-C history - Syntax of an Objective-C program

transcript

TECNOLOGIAS EMERGENTES EM JOGOSEngenharia em Desenvolvimento de Jogos Digitais - 2013/2014

February 18, 2014

Daniela da Cruz

AGENDA

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

2

AGENDA

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

2

THE IOS ARCHITECTURE

THE IOS ARCHITECTURE

→ iOS is the operating system that runs on iPad, iPhone, andiPod touch devices.

→ At the highest level, iOS acts as an intermediary between theunderlying hardware and the apps we create.

→ Apps do not talk to the underlying hardware directly. Instead,they communicate with the hardware through a set ofwell-de�ned system interfaces.

→ These interfaces make it easy to write apps that workconsistently on devices having di�erent hardware capabilities.

4

THE IOS ARCHITECTURE

The implementation of iOS technologies can be viewed as a set oflayers.

5

THE IOS ARCHITECTURE

→ Lower layers contain fundamental services and technologies.

→ Higher-level layers build upon the lower layers and providemore sophisticated services and technologies.

6

THE IOS ARCHITECTURE � CORE OS

The Core OS layer contains the low-level features that most othertechnologies are built upon.

7

THE IOS ARCHITECTURE � CORE OS

The layer provides a variety of services including:

→ low level networking;

→ access to external accessories;

→ and the usual fundamental operating system services such asmemory management, �le system handling and threads.

8

THE IOS ARCHITECTURE � CORE SERVICES

The iOS Core Services layer provides much of the foundation onwhich the other layers are built.

9

THE IOS ARCHITECTURE � CORE SERVICES

Key among these services are the Core Foundation and Foundationframeworks, which de�ne the basic types that all apps use.

This layer also contains individual technologies to support featuressuch as location, iCloud, social media, and networking.

10

THE IOS ARCHITECTURE � MEDIA

The Media layer contains the graphics, audio, and videotechnologies you use to implement multimedia experiences in ourapps.

The technologies in this layer make easier to build apps that lookand sound great.

11

THE IOS ARCHITECTURE � COCOA

The Cocoa Touch layer contains key frameworks for building iOSapps.

These frameworks de�ne the appearance of your app.

They also provide the basic app infrastructure and support for keytechnologies such as multitasking, touch-based input, pushnoti�cations, and many high-level system services.

12

OBJECTIVE-C

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

14

HISTORICAL CONTEXT

→ 1972 � C programming language

→ 1980 � SmallTalk (�rst OO language)

→ 1983 � C++ (C extension with OO support)

→ 1986 � Objective-C (C extension with concepts fromSmallTalk)

15

WHY OBJECTIVE-C?

→ Was chosen as the main language in NeXT company foundedby Steve Jobs to develop the operating System NeXTStep

→ In 1996, Apple buys NeXT and starting the development ofMac OS X (2001) using Objective-C

Objective-C is the native programming language for Apple's iOSand OS X operating systems.

16

OBJECTIVE-C

It's a compiled, general-purpose language capable of buildingeverything from command line utilities to animated GUIs todomain-speci�c libraries.

17

OBJECTIVE-C

Objective-C is a strict superset of C, which means that it's possibleto seamlessly combine both languages in the same source �le.

In fact, Objective-C relies on C for most of its core languageconstructs, so it's important to have at least a basic

foundation in C before tackling the higher-level aspects of thelanguage.

18

OBJECTIVE-C

Like C++, Objective-C was designed to add object-orientedfeatures to C, but the two languages accomplished this usingfundamentally distinct philosophies.

→ Objective-C is more dynamic, deferring most of its decisions torun-time rather than compile-time.

→ Objective-C is also known for its verbose naming conventions.

19

OBJECTIVE-C

C++

1 john->drive("Corvette", "Mary's House")

Objective-C

1 [john driveCar:@"Corvette" toDestination:@"Mary's House"]

Objective-C method calls read more like a human language

than a computer one.

20

OBJECTIVE-C

As with plain old C programs, the main() function serves as theroot of an Objective-C application.

An autoreleasepool implements simple garbage collection for reference-counted objects. It temporarily

takes ownwership of reference-counted objects that nobody else wants to take ownership of and releases

them at a later, appropriate point in time.

21

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

22

ID TYPE

The id type is the generic type for all Objective-C objects. You canthink of it as the object-oriented version of C's void pointer(void*).

And, like a void pointer, it can store a reference to any type ofobject.

id mysteryObject = @"An NSString object";

23

CLASS TYPE

Objective-C classes are represented as objects themselves, using aspecial data type called Class.

This lets you, for example, dynamically check an object's type atruntime (introspection � for later discussion).

Class targetClass = [NSString class];

id mysteryObject = @"An NSString object";

if ([mysteryObject isKindOfClass:targetClass]) {

NSLog(@"Yup! That's an instance of the target class");

}

24

SEL TYPE

The SEL data type is used to store selectors, which areObjective-C's internal representation of a method name.

For example, the following snippet stores a method calledsayHello in the someMethod variable. This variable could be usedto dynamically call a method at runtime.

SEL someMethod = @selector(sayHello);

25

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

26

FOUNDATION FRAMEWORK � DATA TYPES (PART I)

NSObject � is the root class of most Objective-C class hierarchies.

Is the base class for pretty much every object in the iOS SDK.

27

FOUNDATION FRAMEWORK � DATA TYPES

BOOL � used for representing Boolean (YES or NO are BOOLtypes allowed).

BOOL myBOOLyes = YES;

BOOL myBOOLno = NO;

28

FOUNDATION FRAMEWORK � DATA TYPES

NSString � used for representing a string instead of C language'schar* type.

→ An NSString instance can not be modi�ed! They areimmutable.

→ Tons of utility functions available (case conversion, URLs,substrings, type conversions, etc.).

NSString* hi = @"Hi";

29

FOUNDATION FRAMEWORK � DATA TYPES

NSMutableString � Mutable version of NSString. (Somewhatrarely used.)

NSMutableString * str1 = [NSMutableString

stringWithString:@"Hello World"];

30

FOUNDATION FRAMEWORK � DATA TYPES

NSNumber � Object wrapper around primitive types like int,float, double, BOOL, etc.

NSNumber *num = [NSNumber numberWithInt:36];

float f = [num floatValue]; // would return 36 as a float

// (i.e. will convert types)

31

FOUNDATION FRAMEWORK � DATA TYPES

NSValue � Generic object wrapper for other non-object datatypes.

// CGPoint is a C struct

CGPoint point = CGPointMake(25.0, 15.0);

NSValue *pointObject = [NSValue valueWithCGPoint:point];

32

FOUNDATION FRAMEWORK � DATA TYPES

NSDate � Used to �nd out the time right now or to store past orfuture times/dates.

An NSDate object represents a speci�c point in time, independentof any particular calendrical system, time zone, or locale.

Internally, it just records the number of seconds from an arbitraryreference point (January 1st, 2001 GMT).

NSDate *now = [NSDate date];

33

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

34

POINTERS

All Objective-C objects are referenced as pointers.

An NSString object must be stored as a pointer, not a normalvariable:

NSString *model = @"Honda";

35

POINTERS

There is a slight di�erence between C and Objective-C.

Whereas C uses NULL, Objective-C de�nes its own macro, nil, asits null object.

NSString *anObject; // An Objective-C object

anObject = NULL; // This will work

anObject = nil; // But this is preferred

int *aPointer; // A plain old C pointer

aPointer = nil; // Don't do this

aPointer = NULL; // Do this instead

36

NIL VERSUS NULL

Objective-C's nill keyword is similar to NULL in other languageslike C and Java.

The di�erence is that it is perfectly safe to call methods on nil.

If any method that returns an object is called on nill, we willreceive a nil back.

37

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

38

CLASSES

When we de�ne a class, we de�ne a blueprint for a data type.

This doesn't actually de�ne any data, but it does de�ne what theclass name means, that is:

→ what an object of the class will consist of; and

→ what operations can be performed on such an object.

39

CLASSES � INTERFACE

An interface declares the public properties and methods of a class.

@interface Photo : NSObject

{

// Protected instance variables (not recommended)

}

// Properties and Methods

@end

Protected variables can be de�ned inside of the curly braces, butmost developers treat instance variables as implementation detailsand prefer to store them in the .m �le instead of the interface.

40

CLASSES � INTERFACE

When declaring a method, ask yourself:

→ Does the method apply to only one instance or all instances

of the class?

If it applies to all instances, it's usually better as a class method.

Class methods are preceded by a minus (-) symbol.

Instance methods are preceded by a plus (+) symbol.

41

CLASSES � INTERFACE

Example:

@interface Photo : NSObject

- (NSString*) caption;

- (NSString*) photographer;

- (void) setCaption: (NSString*)input;

- (void) setPhotographer: (NSString*)input;

@end

42

CLASSES � IMPLEMENTATION

The @implementation directive is similar to @interface, exceptyou don't need to include the super class.

@implementation Photo {

// Private instance variables

}

// Methods

@end

The instance variables are private and are only accessible inside theclass implementation.

43

CLASSES � IMPLEMENTATION

Continuation of previous example:

@implementation Photo

{

NSString* caption;

NSString* photographer;

}

- (NSString*) caption { return caption; }

- (NSString*) photographer {

return photographer;

}

@end

44

CLASSES � IMPLEMENTATION

The getters themselves are very simple. They just return theinstance variable.

A setter's job is to swap the old value with the new one.

Objective-C objects are di�erent than an int or float. When youassign an object to a variable, it does not get the value; it gets areference to the object.

45

CLASSES � IMPLEMENTATION

- (void) setCaption: (NSString*) input {

[caption autorelease];

[input retain];

caption = input;

}

46

CLASSES � IMPLEMENTATION

1. [caption autorelease]

We no longer need the old NSString object that caption refersso, so we call autorelease on it.

2. [input retain]

We call retain on the input object because we are going toassign it to the instance variable and need it to stay around.

3. caption = input

Finally we set the caption instance variable to be equal toinput.

47

DO I ALWAYS NEED TO DO THIS?

NO

but only if you choose Automatic Reference Counting (ARC) to beused in your project!!!

48

CLASSES � IMPLEMENTATION

Classes usually have an init method to set initial values for itsinstance variables or other setup tasks.

- (id) init {

[self setCaption:@"Default Caption"];

[self setPhotographer:@"Daniela da Cruz"];

return self;

}

49

CLASSES � IMPLEMENTATION

1. Instance variables are set to nil automatically, so inside thebrackets, we set default values for caption andphotographer.

2. Any init method we create has to return self at the end.Our implementation calls to the superclass version of initand captures the result, so we need to actually return the newobject to whoever requested it.

50

CLASSES � INIT

Straight from Apple's o�cial documentation:

There are several critical rules to follow when implementing aninit method that serves as a class's sole initializer or, if there aremultiple initializers, its designated initializer:

1. Always invoke the superclass (super) initializer �rst.

2. Check the object returned by the superclass. If it is nil, theninitialization cannot proceed; return nil to the receiver.

3. After setting instance variables to valid initial values, returnself.

51

CLASSES � INIT

The basic format of a method to override the initializer looks asfollows:

-(id)init

{

self = [super init];

if (self != nil)

{

// Initialization code here

}

return self;

}

52

CLASSES � DESIGNATED INITIALIZER

When working with a class that has more than one initializationmethod, it's important that one of the initializers drives the wholeprocess.

Put another way, only one of the initializer methods does theactual work of calling the super class initializer and initializing theinstance variables of the object.

A general rule of thumb (although not always the case) is that thedesignated initializer is the initializer with the most parameters.

53

CLASSES � DESIGNATED INITIALIZER

@implementation Photo

// = Designated initializer =

-(id)initWithCaptionAndPhotographer: (NSString *)inCaption

photographer:(NSString *)inPhotographer

{

if (self = [super init])

{

[self setCaption:inCaption];

[self setPhotographer:inPhotographer];

}

return self;

}

54

CLASSES � DESIGNATED INITIALIZER

-(id)initWithCaption: (NSString *)inCaption

{

return [self initWithCaptionAndPhotographer:inCaption

photographer:nil];

}

-(id)init

{

return [self initWithCaption:nil];

}

@end

55

CLASSES

Some notes:

→ All classes are derived from the base class called NSObject.

→ NSObject it is the superclass of all Objective-C classes.

→ It provides basic methods like memory allocation andinitialization.

→ Getters usually don't include the �get� keyword in methodname.

→ Init always return �self� at the end.

56

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

57

NAMESPACES

Objective-C does not support namespaces, which is why the Cocoafunctions require pre�xes like NS, CA, AV, etc to avoid namingcollisions.

The recommended convention is to use a three-letter pre�x for yourapplication-speci�c classes (e.g., XYZCar).

58

1. The iOS architecture

2. Objective-C

2.1 History

2.2 Objective-C primitives

2.3 Foundation Framework � Data Types (Part I)

2.4 Pointers

2.5 Classes

2.6 Namespaces

2.7 Utilities

59

UTILITIES � NSLOG

NSLog is used for printing a statement.

It will be printed in device logs and debug console in release anddebug modes respectively.

Format Speci�ers:

→ %i, %d � signed integer

→ %u � unsigned integer

→ %f � �oat

→ %@ � object

60