ios training (basic)

Post on 21-Oct-2014

312 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

Yahoo! Confidential 1

iOS Training (Basics)

Yahoo! Confidential

Gurpreet SinghSriram Viswanathan

Yahoo! Confidential

Topics

Getting Started Introduction to Xcode and Application settings Understanding App execution flow

Introduction to Objective-C Writing your First iPhone Application

Introduction to Interface Builder Outlets and Actions Storyboards Using the iPhone/iPad Simulator

2

Yahoo! Confidential

Some Interesting Facts

What does ‘i’ stands for in iPhone? iPhone 5 was world’s best selling smartphone in Q4 2012, iPhone

5 and iPhone 4S put together accounted for 1 in every 5 smartphones shipped in Q4.

Total iPhones sold till date – 250 million Total iPads sold till date – 100 million People spend $1 million / day in Apple App store. App store has 8 lacs active apps as of March 2013 40 billion app downloads as of March 2013

3

Yahoo! Confidential

Topics

Getting Started Introduction to Xcode and Application settings Understanding App execution flow

Introduction to Objective-C Writing your First iPhone Application

Introduction to Interface Builder Outlets and Actions Storyboards Using the iPhone/iPad Simulator

4

Yahoo! Confidential

Introduction to Xcode

Xcode

5

Yahoo! Confidential

Topics

Getting Started Introduction to Xcode and Application settings Understanding App execution flow

Introduction to Objective-C Writing your First iPhone Application

Introduction to Interface Builder Outlets and Actions Storyboards Using the iPhone/iPad Simulator

6

Yahoo! Confidential

Understanding App Execution Flow

App execution flow

7

Yahoo! Confidential

Understanding App Execution Flow

8

Not running

Inactive

Active

Background

Suspended

Foreground

Yahoo! Confidential

App Delegate Methods

application:willFinishLaunchingWithOptions

application:didFinishLaunchingWithOptions

applicationDidBecomeActive

applicationWillResignAcitve

applicationDidEnterBackground

applicationWillEnterForeground

applicationWillTerminate

9

Yahoo! Confidential

App Launch Cycle

10

User taps icon

main()

UIApplicationMain()

Load main UI File

First Initialization

Restore UI state

Final Initialization

Activate the App

application:willFinishLaunchingWithOptions

Various methods

application:didFinishLaunchingWithOptions

application:didBecomeActive

Event Loop Handle Events

Yahoo! Confidential

Topics

Getting Started Introduction to Xcode and Application settings Understanding App execution flow

Introduction to Objective-C Writing your First iPhone Application

Introduction to Interface Builder Outlets and Actions Storyboards Using the iPhone/iPad Simulator

11

Yahoo! Confidential

Objective C Basics

Objective C is layered on top of C language Is a superset of C Provides object-oriented capabilities

NeXT Software licensed Objective C in 1988 Apple acquired NeXT in 1996 Today it is the native language for developing applications for Mac OS X

and iOS All of the syntax for non-object-oriented operations (including primitive

variables, expressions, function declarations) are identical to that of C While the syntax for object-oriented features is an implementation of

messaging. You might find its syntax a bit complex in starting but will get used to as

you progress.

12

Yahoo! Confidential

Objective C Basics

Creating objects

In other languages, you create objects like this: object = new Class();

The same in Objective C will look likeobject = [[Class alloc] init];

There might be some cases when you may want to pass some input while creating objects.

In other languages you pass the input to the constructor like this: object = new Class(2);

The same in Objective C you will do the same like thisobject = [[Class alloc] initWithInt:2];

13

Yahoo! Confidential

Objective C Basics

Some points to note about objects in Objective C

All object variable are pointers

Object must be alloc'ed and init'ed

When you declare a variable to store an object you need to mention type of object it will hold.

Class *object; object = [[Class alloc] init];

Keyword id is just a way of saying any object id object; object = [[Class alloc] init];

id doesn't use pointer notation

Keyword nil just means no object Class *object = nil;

14

Yahoo! Confidential

Objective C Basics

Declaring methods

A simple method declaration in other languages will look likesetX(n)

or

setX (int n);

or

void setX (int n);

The same in Objective C will look like- (void) setX: (int) n;

15

Yahoo! Confidential

Objective C Basics

16

- (void) setX: (int) n;Method type:

+ = class method- = instance method

Return type Method name Argument nameArgument type

Method declaration explained

Yahoo! Confidential

Objective C Basics

Calling methods

A simple method call in other languages will look likeoutput = object.method();output = object.method(inputParameter);

The same in Objective C will look likeoutput = [object method];output = [object method:inputParameter];

17

Yahoo! Confidential

Objective C Basics

Nested method calls

In many languages, nested method or method calls look like this: object.function1 ( object.function2() );

The same in Objective C will look like[object function1:[object function2]];e.g. [[Class alloc] init]

Multi-input methods

A simple multi-input method call in other languages will look likeobject.setXAndY(3, 2);

The same in Objective C will look like[object setX:3 andY:2];

18

Yahoo! Confidential

Objective C Basics

19

[object setX:3 andY:2]Beginning Method

Call SyntaxEnding Method Call SyntaxObject of the Class

containing the method

First named parameter

First parameter value Second parameter

value

Second named parameter

Multi-input methods explained

Yahoo! Confidential

Objective C Basics

Creating classes

The specification of a class in Objective-C requires two distinct pieces: the interface and the implementation.

The interface portion contains the class declaration and defines the instance variables and methods associated with the class.

The interface is usually in a .h file.

The implementation portion contains the actual code for the methods of the class.

The implementation is usually in a .m file.

When you want to include header files in your source code, you typically use a #import directive.

This is like #include, except that it makes sure that the same file is never included more than once.

20

Yahoo! Confidential

Objective C Basics

Example:

@interface Movie: NSObject { NSString *name;}

- (id) initWithString: (NSString *) movieName;+ (Movie *) createMovieWithName: (NSString *) movieName;

@end

21

Yahoo! Confidential

Objective C Basics

#import Movie.h;

@implementation Movie

- (id) initWithString: (NSString *) movieName { self = [super init]; if (self) { name = movieName; } return self; }

+ (Movie *) createMovieWithName: (NSString *) movieName { return [[self alloc] initWithString: movieName]; }

@end Same as this (keyword) in other languages

22

Yahoo! Confidential

Objective C Basics

Some points to note about #import

Movie.m file includes Movie.h file.

Wherever we want to use Movie object we import Movie.h file (we never import Movie.m file)

Use @class to avoid circular reference (class A needs to import class B and class B needs to import class A).

@class B; @interface A: NSObject - (B*) calculateMyBNess; @end

@class A; @interface B: NSObject - (A*) calculateMyANess; @end

This concept is called forward declaration, tells compiler trust me there is class called class B

23

Yahoo! Confidential

Objective C Basics

There are some issues in previous example (Movie Class)

By default all methods are public in objective C

By default all instance variables are private in objective C

What if I directly call initWithString instead of createMovieWithName?

We need to make initWithString private.

Secondly, what if I don’t know the movie name upfront and I want to create the Movie object and then assign the name of movie later?

We have to provide public methods (getter and setter) to get and set the movie name.

24

Yahoo! Confidential

Objective C Basics

Using Private Methods

@interface Movie: NSObject { NSString *name;}

- (id) initWithString: (NSString *) movieName;+ (Movie *) createMovieWithName: (NSString *) movieName;

@end

25

Yahoo! Confidential

Objective C Basics

#import Movie.h;

@interface Movie (private) - (id) initWithString: (NSString *) movieName;@end

@implementation Movie - (id) initWithString: (NSString *) movieName { self = [super init]; if (self) { name = movieName; } return self; } + (Movie *) createMovieWithName: (NSString *) movieName { return [[self alloc] initWithString: movieName]; }@end

26

Yahoo! Confidential

Objective C Basics

Adding getter and setter methods

Note, in objective C, as per convention the getter method for a variable named ‘age’ is not ‘getAge’, in fact it is called as ‘age’ only.

But, the setter method for variable ‘age’ will be called as ‘setAge’.

So in our example, getter method will be movie.name and setter method will be movie.setName

27

Yahoo! Confidential

Objective C Basics

Adding getter and setter methods

@interface Movie: NSObject { NSString *name;}

- (NSString *) name;- (void) setName: (NSString *) movieName;

+ (Movie *) createMovieWithName: (NSString *) movieName;

@end

28

Yahoo! Confidential

Objective C Basics

@implementation Movie - (NSString *) name { return name; } - (void) setName: (NSString *) movieName { if (![name isEqualToString: movieName]) { name = movieName; } } …@end

UsageMovie *myMovie = [[Movie alloc] init];[myMovie setName:@”Dhoom”]; NSString *movieName = [myMovie name];

29

Yahoo! Confidential

Objective C Basics

Using @property and @synthesize directive

Adding getter / setter methods for all the instance variables can become a tedious task.

Apple provide a simple way for this, you can use @property directive Benefits

You do not have to write getter and setter methods yourself. You can define the "assigning behavior" (namely copy, strong, weak,

nonatomic)

Keywords:• copy: The object is copied to the ivar when set• strong: The object is retained on set• weak: The object's pointer is assigned to the ivar when set and will be set to nil

automatically when the instance is deallocated• nonatomic: The accessor is not @synchronized (threadsafe), and therefore faster• atomic: The accessor is @synchronized (threadsafe), and therefore slower

30

Yahoo! Confidential

Objective C Basics

Using @property and @synthesize directive

@interface Movie: NSObject { NSString *name;}

@property (nonatomic, strong) NSString *name;

- (NSString *) name;- (void) setName: (NSString *) movieName;

+ (Movie *) createMovieWithName: (NSString *) movieName;

@end

31

Yahoo! Confidential

Objective C Basics

@implementation Movie @synthesize name;

- (NSString *) name { return name; } - (void) setName: (NSString *) movieName { if (![name isEqualToString: movieName]) { name = movieName; } } …@end

32

Yahoo! Confidential

Objective C Basics

To sum up:

NSString *name; - declares an instance variable 'name'

@property (nonatomic, strong) NSString *name; - declares the accessor methods for 'name'

@synthesize name; - implements the accessor methods for 'name'

33

Yahoo! Confidential

Objective C Basics

Using strings (NSString class)

NSString *movieName = @”Dhoom”;

The @ symbolOk, why does this funny @ sign show up all the time? Well, Objective-C is an extension of the C-language, which has its own ways to deal with strings. To differentiate the new type of strings, which are fully-fledged objects, Objective-C uses an @ sign.

A new kind of stringHow does Objective-C improve on strings of the C language? Well, Objective-C strings are Unicode strings instead of ASCII strings. Unicode-strings can display characters of just about any language, such as Chinese, as well as the Roman alphabet.

A C string is simply a series of characters (a one-dimensional character array) that is null-terminated, whereas an NSString object is a complete object with class methods, instance methods, etc.

Note: It is possible (but not recommended) to use C language strings in Objective C.

34

Yahoo! Confidential

Objective C Basics

Using ‘stringWithFormat’

NSString *movieName = [NSString stringWithFormat:@”Dhoom %d”, 2]; // Dhoom 2

Specifiers:%d Signed 32-bit integer (int)%f 64-bit floating-point number (double)%@ Objective-C object

Complete list of format specifiers is available here.

Introduction to NSLog

NSLog(@”Movie name is %@”, movieName);

Format specifiers same as ‘stringWithFormat’. Used for debugging Same as error_log in PHP or console.log in JavaScript Note the use of round brackets unlike other method calls in objective C

35

Yahoo! Confidential

Objective C Basics

Using arrays (NSArray class)

Provide random access The objects contained in an array do not all have to be of the same type.

Factory methods (static methods that build array from given parameters):+ (id)array Creates and returns an empty array+ (id)arrayWithObjects Creates and returns an array containing a given objectLot of such factory methods available

Accessing the NSArray- (BOOL)containsObject:(id)anObject Returns true if a given object is found in the array- (NSUInteger)count Returns the size of the array- (id)lastObject Returns the last object in the array- (id)objectAtIndex:(NSUInteger)index Returns the object at a given index.

36

Yahoo! Confidential

Objective C Basics

Introduction to NSMutableArray

NSArray is immutable (content of array cannot be modified without recreating it) You can create mutable arrays (NSMutableArray) if you want to add or remove elements

after creating.

Additional functions to manipulate the arrayinsertObject:atIndex:removeObjectAtIndex:addObject:removeLastObjectreplaceObjectAtIndex:withObject:

37

Yahoo! Confidential

Objective C Basics

Introduction to NSDictionary

NSDictionary are like Maps and Hashes in other languages Key-value pairs It is an unordered collection of objects

Factory methods (static methods that build array from given parameters):+ (id)dictionary Creates and returns an empty dictionary+ (id)dictionaryWithObjects: forKeys: Creates and returns a dictionary containing entries

constructed from the contents of an array of keys and an array of values

Lot of such factory methods available

Accessing the NSDictionary– allKeys Returns a new array containing the dictionary’s keys.– allValues Returns a new array containing the dictionary’s values.– objectForKey: Returns the value associated with a given key.

38

Yahoo! Confidential

Objective C Basics

Introduction to NSMutableDictionary

Similar to NSArray, NSDictionary is also immutable You can create mutable dictionary (NSMutableDictionary) if you want to add or remove

objects after creating.

Additional functions to manipulate the dictionarysetObject:forKey:removeObjectForKey:removeAllObjects:removeObjectsForKeys:

Points to note: NSArray and NSDictionary only store objects So if you want to store numbers then you have to convert it to NSNumber Use NSNull for empty values

39

Yahoo! Confidential

Topics

Getting Started Introduction to Xcode and Application settings Understanding App execution flow

Introduction to Objective-C Writing your First iPhone Application

Introduction to Interface Builder Outlets and Actions Storyboards Using the iPhone/iPad Simulator

40

top related