iphone course 1
DESCRIPTION
TRANSCRIPT
iPhone Application Development 1Janet Huang2011/11/23
ALL Schedule
11/23 - iPhone SDK- Objective-C Basic- Your First iPhone Application
11/30 - MVC design & UI- GPS/MAP Application (CoreLocation & MapKit)- Google Map API- LBS Application
12/07 - Network service - Facebook API- LBS + Facebook Application
How to study?
- Stanford CS193p - videos in iTunes U - all resources on website
- Apple official document
- Good book - iOS Programming The Big Nerd Ranch Guide
Today’s Topics
• iPhone SDK
• Objective-C
• Common Foundation Class
• Your First iPhone Application
iPhone SDK
• Xcode Tools
• Xcode
• Instruments
• iOS Simulator
• iOS Developer Library
iPhone OS overview
Platform Components
OOP Vocabulary
• Class: define the grouping of data and code, the “type” of an object
• Instance: a specific allocation of a class
• Method: a “function” that an object knows how to perform
• Instance variable: a specific piece of data belonging to an object
OOP Vocabulary• Encapsulation
• keep implementation private and separate from interface
• Polymorphism
• different object, same interface
• Inheritance
• hierarchical organization, share code, customize or extend behaviors
Inheritance
- Hierarchical relation between classes
- Subclass “inherit” behavior and data from superclass
- Subclasses can use, augment or replace superclass methods
Objective-C
• Classes & Objects
• Messaging
• Properties
• Protocols
Classes and Instances• In obj-c, classes and instances are both
objects
• class is the blueprint to create instances
Classes and Objects
• Classes declare state and behavior
• State (data) is maintained using instance variables
• Behavior is implemented using methods
• instance variables typically hidden
• accessible only using getter/setter methods
Define a Class
#import <Foundation/Foundation.h>@interface Person : NSObject { // instance variables NSString *name; int age;} // method declarations - (NSString *)name; - (void)setName:(NSString *)value; - (int)age; - (void)setAge:(int)age; - (BOOL)canLegallyVote; - (void)castBallot;@end
#import "Person.h" @implementation Person - (int)age { return age; } - (void)setAge:(int)value {age = value; } //... and other methods @end
in .h file in .m file
public header private implementation
A class declaration
Object Creation• Two steps
• allocate memory to store the object
• initialize object state
+alloc
-init
class method that knows how much memory is needed
instance method to set initial values, perform other setup
Create = Allocate + Initialize
Person *person = nil;person = [[Person alloc] init]
#import “Person.h”
@implementation Person
- (id)init { if(self = [super init]){ age = 0; name = @”Janet”; // do other initialization }}
Implementing your own -init method
Messaging
• Class method and instance method
• Messaging syntax
Terminology• Message expression
• Message
• Selector
• Method
[receiver method: argument]
[receiver method: argument]
[receiver method: argument]
The code selected by a message
Method declaration syntax
Class and Instance Methods
• instances respond to instance methods
• classes respond to class methods
- (id) init;- (float) height;- (void) walk;
+ (id) alloc;+ (id) person;+ (Person *) sharedPerson;
Messaging• message syntax
• message declaration
• call a method or messaging
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
[myArray insertObject:anObject atIndex:0]
[receiver message]
[receiver message:argument]
[receiver message:arg1 andArg:arg2]
Instance Variables• Scope
• Scope syntax
@protected
@public@private
only the class and subclass can accessonly the class can accessanyone can access
default
@interface MyObject : NSObject { int foo;@private int eye;@protected int bar;@public int forum; int apology;@private int jet; }
Protected: foo & barPrivate: eye & jetPublic: forum & apology
• Forget everything on the previous slide!Mark all of your instance variables @private.Use @property and “dot notation” to access instance variables.
Accessor methods• Create getter/setter methods to access instance
variable’s value
• Now anyone can access your instance variable using “dot syntax”
@interface MyObject : NSObject {@privateint eye; }- (int)eye;- (void)setEye:(int)anInt;@end
someObject.eye = newEyeValue; // set the instance variableint eyeValue = someObject.eye; // get the instance variable’s current value
* Note the capitalization - instance variables always start with lower case - the letter after “set” MUST be capitalized
Properties
Let compiler to help you generate setter/getter method declarations
@property
@interface MyObject : NSObject {@privateint eye; }@property int eye;- (int)eye;- (void)setEye:(int)anInt;@end
@interface MyObject : NSObject {@privateint eye; }@property int eye;
@end
Properties
• An @property doesn’t have to match an instance variable
@interface MyObject : NSObject {@privateint p_eye; }@property int eye;@end
@interface MyObject : NSObject {}@property int eye;@end
*They are all perfectly legal!
Properties• Don’t forget to implement it after you
declare
@interface MyObject : NSObject {@privateint eye; }@property int eye;@end
@implementation MyObject- (int)eye { return eye;}- (void)setEye:(int)anInt {eye = anInt; }@end
in .h file in .m file
Properties
Let compiler to help you with implementation
@synthesize
@interface MyObject : NSObject {@privateint eye; }@property int eye;@end
in .h file in .m file
@implementation MyObject@synthesize eye;- (int)eye { return eye;}- (void)setEye:(int)anInt {eye = anInt; }@end
Properties
• Be careful!!
- (void)setEye:(int)anInt{ self.eye = anInt;}
What’s wrong?
Can happen with the getter too ...
Infinite loop!!! :(
- (int)eye { if (self.eye > 0) { return eye; } else { return -1; } }
Protocols
@interface MyClass : NSObject <UIApplicationDelegate, AnotherProtocol> {}@end
@protocol MyProtocol- (void)myProtocolMethod;@end
Dynamic and static typing
• Dynamically-typed object
• Statically-typed object
id anObject not id *
Person * anObject
The null pointer: nil
• explicitly
• implicitly
• assignment
• argument
• send a message to nil
if (person == nil) return;
if (!person) return;
person = nil;
person = nil;[person castBallot];
[button setTarget: nil];
BOOL typedef• Obj-C uses a typedef to define BOOL as a
type
• use YES or NO
BOOL flag = NO;if (flag == YES)if (flag)if (!flag)if (flag != YES)flag = YES;flag = 1;
Foundation Framework
• NSObject
• Strings
• NSString
• NSMutableString
• Collections
• Array
• Dictionary
• Set
NSObject
• Root class
• Implements many basics
• memory management
• introspection
• object equality
- (NSString *)description is a useful method to override (it’s %@ in NSLog()).
String Constants
• C constant strings
• Obj-C constant strings
• Constant strings are NSString instances
“c simple strings”
@“obj-c simple strings”
NSString *aString = @“Hello World!”;
Format Strings• use %@ to add objects (similar to printf)
• used for logging
NSString *aString = @”World!”; NSString *result = [NSString stringWithFormat: @”Hello %@”, aString];
NSLog(@”I am a %@, I have %d items.”, [array className], [array count]);
result: Hello World!
Log output: I am NSArray, I have 5 items.
NSString• Create an Obj-C string from a C string
• Modify an existing string to be a new string
NSString *fromCString = [NSString stringWithCString:"A C string"encoding:NSASCIIStringEncoding];
NSString *myString = @”Hello”;NSString *fullString;fullString = [myString stringByAppendingString:@” world!”];
- (NSString *)stringByAppendingString:(NSString *)string;- (NSString *)stringByAppendingFormat:(NSString *)string;- (NSString *)stringByDeletingPathComponent;
for example:
NSMutableString• Mutable version of NSString
• Allows a string to be modified
• Common methods
NSMutableString *newString = [NSMutableString string];[newString appendString:@”Hi”];[newString appendFormat:@”, my favorite number is: %d”,[self favoriteNumber]];
+ (id)string;- (void)appendString:(NSString *)string;- (void)appendFormat:(NSString *)format, ...;
for example:
MVC
controller
model view
outlet
target
delegate
data sources
shoulddid
will
count
data
action
Notification & KVO
General process for building iPhone application
1. Create a simple MVC iPhone applica5on2. Build interfaces using Interface builder3. Declara5ons
a. Declaring instance variablesb. Declaring methods
4. Make connec5onsa. SeDng a pointerb. SeDng targets and ac5ons
5. Implemen5ng methodsa. Ini5al methodb. Ac5on methods
6. Build and run on the simulator7. Test applica5on on the device