Post on 10-May-2015
description
iOS Programming - 101Xcode, Obj-C, iOS APIs
Subhransu Behera @subhransu
subh@subhb.org
Xcode
Development Tools
Xcode Interface Builder iOS Simulator InstrumentsIDE UI Design Simulate Apps Monitor Performance
IB is built-in in Xcode 4
Xcode IDE
• Editors // source editor & UI editor
• Single window interface
• Automatic error identification and correction
• Assistance editing
• Source control
Navigation area
Editor areaUtility area
Debug area
Run on Simulator or Device
Switch editors and views
Obj-C (Object Allocation)
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.
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
• 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.
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];
Message Passing
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];
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.
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
Message Passing
• [receiver message];• [receiver message:argument]; • [receiver message:arg1 andArg:arg2];
Objective-C Properties
Declared Properties
• Provides a getter and a setter method
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
Manual Implementation without Properties
// manual getter method
-(NSString *)getSnailName { return snailName;}
// manual setter method
-(void)setSnailName:(NSString *)name { if (![name isEqualToString:snailName]) { snailName = name; }}
Doing it using Properties
@property (attributes) type name;
Atomicity Writability, Ownership
# atomic# nonatomic
# readonly# strong, weak
Properties
@property (nonatomic, strong) NSString *snailName;
@property int animationInterval;
@property int animationInterval;
Core Obj-C Classes
• NSNumber, NSInteger
• NSString, NSMutableString
• NSArray, NSMutableArray
• NSSet, NSMutableSet
• NSDictionary, NSMutableDictionary
Obj-C Classes
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
Strings
• Have seen glimpse of it in all our NSLog messages
• NSLog(@"Objective C is Awesome");
• NSString *snailName = [[NSString alloc] init];
Strings Methods
[NSString stringWithFormat:@"%d", someInteger];
[NSString stringWithFormat:@"My integer %d", someInteger];
[snailName stringByReplacingOccurrencesOfString:@"N" withString:@"P"];
NSString *newString = [myString appendString:@"Another String"];
NSNumbers
NSNumber *animationDuration = [[NSNumber alloc] init];
NSNumber *animationDuration = [[NSNumber alloc] initWithBool:YES];
NSNumber *animationDuration = [[NSNumber alloc] initWithInt:1];
// While creating NSNumbers
NSNumber *myNumber;myNumber = @'Z';myNumber = @YES;myNumber = @1;myNumber = @10.5;
// While evaluating expressions
NSNumber *myNewNumberAfterExpression = @(25 / 6);
NSNumbers
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];
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
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
Learn more about NSSet and NSDictionary
View Controllers
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
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;
}
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!
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.
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
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
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.
Thanks
Subhransu Behera @subhransu
subh@subhb.org