43
iOS Programming - 101 Xcode, Obj-C, iOS APIs Subhransu Behera @subhransu [email protected]

iOS 101 - Xcode, Objective-C, iOS APIs

Embed Size (px)

DESCRIPTION

Learn basics of Xcode, Objective-C syntax, Object allocation, message passing, category, core obj-c classes, how view-controllers work through some basic example apps.

Citation preview

Page 1: iOS 101 - Xcode, Objective-C, iOS APIs

iOS Programming - 101Xcode, Obj-C, iOS APIs

Subhransu Behera @subhransu

[email protected]

Page 2: iOS 101 - Xcode, Objective-C, iOS APIs

Xcode

Page 3: iOS 101 - Xcode, Objective-C, iOS APIs

Development Tools

Xcode Interface Builder iOS Simulator InstrumentsIDE UI Design Simulate Apps Monitor Performance

IB is built-in in Xcode 4

Page 4: iOS 101 - Xcode, Objective-C, iOS APIs

Xcode IDE

• Editors // source editor & UI editor

• Single window interface

• Automatic error identification and correction

• Assistance editing

• Source control

Page 5: iOS 101 - Xcode, Objective-C, iOS APIs
Page 6: iOS 101 - Xcode, Objective-C, iOS APIs

Navigation area

Editor areaUtility area

Debug area

Page 7: iOS 101 - Xcode, Objective-C, iOS APIs

Run on Simulator or Device

Switch editors and views

Page 8: iOS 101 - Xcode, Objective-C, iOS APIs

Obj-C (Object Allocation)

Page 9: iOS 101 - Xcode, Objective-C, iOS APIs

Objective C

• Strict super set of C

• Provide Object Oriented Programming capability to C

• Dynamic Runtime.

• Message passing in stead of method calling

• Can mix-in C & C++ codes with Objective C

• Primary language used by Apple for Mac OSX and iOS application development.

Page 10: iOS 101 - Xcode, Objective-C, iOS APIs

Objective C Class#import <Foundation/Foundation.h>

@interface Cat : NSObject { int numberOfEyes; float lengthOfMyCat; NSString *name; NSString *breed;}

-(void)drinkMilk;-(void)makeACatDanceFor:(int)numberOfSeconds;

@end

Page 11: iOS 101 - Xcode, Objective-C, iOS APIs

• Class declaration starts at @interface and ends at @end

• Cat is the class name that is the name after @interface and before “:”

• NSObject is the name of the super-class

• numberOfEyes, lengthOfMyCat, name, breed are attributes of a Class object.

• drinkMilk and makeACatDanceFor: are methods that a an object of Cat (class) can respond to.

Page 12: iOS 101 - Xcode, Objective-C, iOS APIs

Object Allocation

Cat *myCat = [[Cat alloc] init];

// what exactly happens// 1st line allocates enough memory to hold a cat object

Cat *myCat = [Cat alloc];

// 2nd line initializes the object.

[myCat init];

Page 13: iOS 101 - Xcode, Objective-C, iOS APIs

Message Passing

Page 14: iOS 101 - Xcode, Objective-C, iOS APIs

Message Passing in Obj-C• In other languages you refer this as method calling.

But due to the nature of Obj-C it’s often referred as a message (can refer it as method or function) being passed to an object to make it do something.

• A message is passed to an object with-in square brackets.

[objectName messageName];

• Messages can be piped together. That is a message can be passed to an object is the result of another message.

[[objectName messageOne] messageTwo];

Page 15: iOS 101 - Xcode, Objective-C, iOS APIs

Message Passing Syntax

ptg999

37The @implementation Section

methodtype

returntype

methodname

methodtakes

argument

argumenttype

argumentname

Figure 3.1 Declaring a method

The @implementation SectionAs noted, the @implementation section contains the actual code for the methods youdeclared in the @interface section.You have to specify what type of data is to be storedin the objects of this class.That is, you have to describe the data that members of the classwill contain.These members are called the instance variables. Just as a point of terminology,you say that you declare the methods in the @interface section and that you define them(that is, give the actual code) in the @implementation section.The general format for the@implementation section is as follows:

@implementation NewClassName{

memberDeclarations;}methodDefinitions;

@end

NewClassName is the same name that was used for the class in the @interface section.You can use the trailing colon followed by the parent class name, as we did in the@interface section:

@implementation Fraction: NSObject

However, this is optional and typically not done.The memberDeclarations section specifies what types of data are stored in a

Fraction, along with the names of those data types.As you can see, this section isenclosed inside its own set of curly braces. For your Fraction class, these declarations saythat a Fraction object has two integer members, called numerator and denominator:

int numerator;int denominator;

The members declared in this section are known as the instance variables. Each timeyou create a new object, a new and unique set of instance variables also is created.There-fore, if you have two Fractions, one called fracA and another called fracB, each willhave its own set of instance variables—that is, fracA and fracB each will have its ownseparate numerator and denominator.The Objective-C system automatically keeps trackof this for you, which is one of the nicer things about working with objects.The

take any arguments. In Chapter 7,“More on Classes,” you’ll see how methods that takemore than one argument are identified.

Page 16: iOS 101 - Xcode, Objective-C, iOS APIs

Instance & Class Methods

• Instance responds to instance methods (starts with -)

-(id)init;

-(void)sing;

-(NSString *)description;

• Class responds to class methods (starts with +)

+(id)alloc;

+(void)initEventWithEventName:(NSString *)eventName

Page 17: iOS 101 - Xcode, Objective-C, iOS APIs

Message Passing

• [receiver message];• [receiver message:argument]; • [receiver message:arg1 andArg:arg2];

Page 18: iOS 101 - Xcode, Objective-C, iOS APIs

Objective-C Properties

Page 19: iOS 101 - Xcode, Objective-C, iOS APIs

Declared Properties

• Provides a getter and a setter method

Page 20: iOS 101 - Xcode, Objective-C, iOS APIs

Manual Declaration without Properties

#import <UIKit/UIKit.h>

@interface SnailView : UIImageView { double animationInterval; NSString *snailName;}

// manual declaration of methods

-(NSString *)getSnailName;-(void)setSnailName:(NSString *)name;

@end

Refer to the SnailView.h and SnailView.m in SnailRun sample code

Page 21: iOS 101 - Xcode, Objective-C, iOS APIs

Manual Implementation without Properties

// manual getter method

-(NSString *)getSnailName { return snailName;}

// manual setter method

-(void)setSnailName:(NSString *)name { if (![name isEqualToString:snailName]) { snailName = name; }}

Page 22: iOS 101 - Xcode, Objective-C, iOS APIs

Doing it using Properties

@property (attributes) type name;

Atomicity Writability, Ownership

# atomic# nonatomic

# readonly# strong, weak

Page 23: iOS 101 - Xcode, Objective-C, iOS APIs

Properties

@property (nonatomic, strong) NSString *snailName;

@property int animationInterval;

@property int animationInterval;

Page 24: iOS 101 - Xcode, Objective-C, iOS APIs

Core Obj-C Classes

Page 25: iOS 101 - Xcode, Objective-C, iOS APIs

• NSNumber, NSInteger

• NSString, NSMutableString

• NSArray, NSMutableArray

• NSSet, NSMutableSet

• NSDictionary, NSMutableDictionary

Obj-C Classes

Page 26: iOS 101 - Xcode, Objective-C, iOS APIs

object vs mutable object

Object Mutable Object

• Readonly

• Original Object can not be modified

• However can be copied to another mutable object which can be modified.

• Read-write

• Can add, update, delete original object

Page 27: iOS 101 - Xcode, Objective-C, iOS APIs

Strings

• Have seen glimpse of it in all our NSLog messages

• NSLog(@"Objective C is Awesome");

• NSString *snailName = [[NSString alloc] init];

Page 28: iOS 101 - Xcode, Objective-C, iOS APIs

Strings Methods

[NSString stringWithFormat:@"%d", someInteger];

[NSString stringWithFormat:@"My integer %d", someInteger];

[snailName stringByReplacingOccurrencesOfString:@"N" withString:@"P"];

NSString *newString = [myString appendString:@"Another String"];

Page 29: iOS 101 - Xcode, Objective-C, iOS APIs

NSNumbers

NSNumber *animationDuration = [[NSNumber alloc] init];

NSNumber *animationDuration = [[NSNumber alloc] initWithBool:YES];

NSNumber *animationDuration = [[NSNumber alloc] initWithInt:1];

Page 30: iOS 101 - Xcode, Objective-C, iOS APIs

// While creating NSNumbers

NSNumber *myNumber;myNumber = @'Z';myNumber = @YES;myNumber = @1;myNumber = @10.5;

// While evaluating expressions

NSNumber *myNewNumberAfterExpression = @(25 / 6);

NSNumbers

Page 31: iOS 101 - Xcode, Objective-C, iOS APIs

NSArray & NSMutableArray

NSArray(read-only)

NSMutableArray(read write)

• Manage collections of Objects

• Objects can be anything NSString, NSNumber, NSDictionary, even NSArray itself.

• NSArray creates static array

• NSMutableArray creates dynamic array

NSArray *myArray = [[NSArray alloc] init];

NSArray *myArray = [[NSArray alloc] initWithObjects:Obj1, Obj2, nil];

NSArray *myArray = @[Obj1, Obj2];

Page 32: iOS 101 - Xcode, Objective-C, iOS APIs

getting and setting values

• Values are being accessed using array index

• myArray[2] // will return 3rd object. Index starts from 0

• Value can be set by assigning an Object for an index

• myArray[3] = @"some value"; // will set value for 4th element

Page 33: iOS 101 - Xcode, Objective-C, iOS APIs

insertion & deletion• – count:

• returns number of objects currently in the array

• – containsObject:

• Tells if a given object is present or not

• – addObject:

• Insert a given object at end of the array

• – insertObject:atIndex:

• Insert an object at specified index

• – removeAllObjects:

• Empties the array of all its elements

Page 34: iOS 101 - Xcode, Objective-C, iOS APIs

Learn more about NSSet and NSDictionary

Page 35: iOS 101 - Xcode, Objective-C, iOS APIs

View Controllers

Page 36: iOS 101 - Xcode, Objective-C, iOS APIs

Key Objects in iOS Apps�20>;. �� %8L B5=86GF <A 4A <)- 4CC?<64G<BA

Data Model ObjectsData Model ObjectsData Model Objects

Data Model ObjectsData Model ObjectsViews and UI ObjectsData Model ObjectsData Model ObjectsAdditional Controller

Objects (custom)

Model

Controller

EventLoop

View

UIWindowUIApplication

Root View Controller

Custom Objects

System Objects

Either system or custom objects

Application Delegate(custom object)

$*+5. � .;8 EB?8 B9 B5=86GF <A 4A <)- 4CC?<64G<BA

�.<,;29=287�+3.,=

.;8 UIApplication B5=86G@4A4:8F G;8 4CC?<64G<BA 8I8AG ?BBC 4A7 6BBE7<A4G8FBG;8E ;<:;?8I8? 58;4I<BEF 9BE LBHE 4CC?<64G<BA� 3BH HF8 G;<F B5=86G 4F <F @BFG?LGB 6BA9<:HE8 I4E<BHF 4FC86GF B9 LBHE 4CC?<64G<BATF 4CC84E4A68� 3BHE 6HFGB@4CC?<64G<BA?8I8? 6B78 E8F<78F <A LBHE 4CC?<64G<BA 78?8:4G8 B5=86G J;<6; JBE>F<A G4A78@ J<G; G;<F B5=86G�

UIApplicationB5=86G

.;8 4CC?<64G<BA 78?8:4G8 <F 4 6HFGB@B5=86G G;4G LBH CEBI<78 4G 4CC?<64G<BA ?4HA6;G<@8 HFH4??L 5L 8@5877<A: <G <A LBHE 4CC?<64G<BATF @4<A A<5 9<?8� .;8 CE<@4EL =B5B9 G;<F B5=86G <F GB <A<G<4?<M8 G;8 4CC?<64G<BA 4A7 CE8F8AG <GF J<A7BJ BAF6E88A� .;8UIApplication B5=86G 4?FB ABG<9<8F G;<F B5=86G J;8A FC86<9<6 4CC?<64G<BA?8I8?8I8AGF B66HE FH6; 4F J;8A G;8 4CC?<64G<BA A887F GB 58 <AG8EEHCG87 �5864HF8 B94A <A6B@<A:@8FF4:8� BE FHFC8A787 �5864HF8 G;8 HF8E G4CC87 G;8 "B@8 5HGGBA��

BE @BE8 <A9BE@4G<BA 45BHG G;<F B5=86G F88 R.;8 �CC?<64G<BA �8?8:4G8S��C4:8����

�CC?<64G<BA 78?8:4G8B5=86G

.;8 �BE8 �CC?<64G<BA )5=86GF ������ ����� D���E������995.��7,���55�"201=<�".<.;?.-�

��� $�"

.;8 �BE8 �CC?<64G<BA �8F<:A

Page 37: iOS 101 - Xcode, Objective-C, iOS APIs

when app finishes launching- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

// window is being instantiated self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// view controller is being instantiated self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];

// every app needs a window and a window needs a root view controller self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];return YES;

}

Page 38: iOS 101 - Xcode, Objective-C, iOS APIs

what is this view controller• It is the controller part of M-V-C

• Every view controller has a view

• Your custom view controllers are sub-class of UIViewController class.

• Provides view-management model for your apps.

• Re-size views

• Adjust the contents of views

• Acts on-behalf of views when users interacts!

• Has view-event methods that gets called when view appears and disappears!

Page 39: iOS 101 - Xcode, Objective-C, iOS APIs

View controller view events• – viewDidLoad:

• Called after view has been loaded

• – viewDidUnload:

• After view controller’s view is released or set to nil

• – viewWillAppear:

• When view is about to made visible

• – viewDidAppear:

• When view has been fully transitioned to screen

• – viewWillDisappear: and – viewDidDisappear:

• The counter-part of above 2 methods.

Page 40: iOS 101 - Xcode, Objective-C, iOS APIs

Managing View Rotations

• – shouldAutoRotate

• Whether auto-rotation is supported or not

• Returns a boolean value YES/NO or TRUE/FALSE

• – supportedInterfaceOrientations

• Returns interface orientation masks

• – didRotateFromInterfaceOrientation

• Notifies when rotation happens

Page 41: iOS 101 - Xcode, Objective-C, iOS APIs

Sample Codes

• HelloWorld - Combines two text from text field and display on a label

• SliderExample - Displays current value of a Slider

• Hashes - Displays the number of hashes and creates a geometric structue

• WeatherApp - Provides weather for a given day (hard coded values)

• SnailRun - Makes a snail move in a direction (try changing the direction value)

• MediaPlayer - Plays a local video file

https://www.dropbox.com/s/wqcuusr9p2j913i/SampleCodes.zip

Page 42: iOS 101 - Xcode, Objective-C, iOS APIs

To learn more ...

• Objective C - Read Stephen Kochan’s Book

• Go through “iOS UI Element Usage Guidelines” in iOS Human Interface Guidelines to learn more about the various UI components available and their usage

• Play with Obj-C and iOS lessons from Code School

• Watch iOS Development Videos & WWDC Videos

• Join the community “iOS Dev Scout” facebook group.

Page 43: iOS 101 - Xcode, Objective-C, iOS APIs

Thanks

Subhransu Behera @subhransu

[email protected]