IPhone Tech Talks/Introduction to Objective-C and Cocoa Touch
From ceejayoz
- Matt Drance (App Framework Evangelist)
- Michael Jurewitz (Development Tools and Performance Evangelist)
Contents |
[edit] iPhone OS
- Code Signing
- Single app/process environment
[edit] Sandboxing
- frameworks allow access to some non-sandboxed data
[edit] Memory management
- no swap space
- issues memory warning prompting cleanup
- quit app if exceed
[edit] Objective C
C language with Smalltalk-style syntax --> ObjC
C++:
- fast but static
- compile-time decisions, little runtime flexibility
Objective-C:
- dynamic
- runtime decision making
- runtime class extensions
[edit] Calling a method - class and function/message
[edit] C++
someObject->doSomething();
[edit] Java
someObject.doSomething();
[edit] Objective-C
[someObject doSomething];
can be nested!
[edit] Messaging
-
[Employee newEmployee];
- class, method -
[anEmployee setRaise:200];
- instance of class, method with parameter/argument -
[anEmployee setWork:work withDeadline:today];
- instance, multiple parameters- you know what argument type fits which position, self-documenting
[edit] Selectors
-
[Employee newEmployee]
is 'newEmployee' -
[anEmployee setRaise:200]
is 'setRaise:' -
[anEmployee setWork:work withDeadline:today]
is 'setWork:withDeadline'
[edit] Method dispatch
- class hierarchy (single only, not multiple) - Employee -> Person -> NSObject
- NSObject is the root object, defined in Foundation framework
- Employee gets chance to respond to message, then Person, then NSObject
- 'firstName' method
- in this example, Employee has no firstName method, but Person has a firstName method, so it gets it
- 'description' method
- defined on NSObject
- very basic way to print itself out at commandline / memory
- can override method for debug - output state, etc.
- what happens when no response to message?
- traverses classes again for opportunity to pass to helper object
- exception raised if no helper object to forward to
- exceptions raised only in 'exceptional circumstances' (cute)
[edit] Example: Person class
@interface Person : NSObject { // @interface = 'this is beginning of class defn', Person = class name, NSObject = Person is subclass of NSObject NSString *name; // NS = foundation class (NextStep) int age; NSMutableArray *parents; + (Person *)personWithName:(NSString *)name; // plus = class method, only send within class - (id)initWithName:(NSString *)name; // minus = instance method, only send to instance of class... (id) is return type for method - (int)age; // getter, no need to put get before, just use name itself - (void)setAge:(int)newAge; - (NSArray *)parents; - (void)setParents:(NSArray *)parents; @end
#import "Person.h" // #import prevents multiple includes of same header file @implementation Person // implementation here @end
[edit] Initialising instance
- (id)init { if (self = [super init]) { // making sure didn't get back invalid object name = @"New Person"; // set up instance var (in this case, a string literal - at sign + quoted string) parents = [[NSArray alloc] init]; // set up instance var, an array... alloc = allocate space, then initialise with init } return self; // return instance to whoever asked for it }
super = send messages to superclass
[edit] Getting and setting simple type
- (int)age { return age; }
- (void)setAge:(int)newAge { age = newAge; }
[edit] Getting and setting objects
- (NSString *)name { return name; }
[edit] Memory management
- runtime tracks object's retain count for entire lifetime of object (starts at 1 on creation)
- need to stick around? send it the retain message (
-retain) - done with it? release it with </code>-release</code>
- once no longer needed by any part of system, cleared out of memory!
MJFoo *myFoo = [[MJFoo alloc] init]; - retain count 1
[myFoo retain]; - retain 2
[myFoo release]; - retain 1
[myFoo release]; - retain 0, cleared from memory
[edit] Autorelease pools
- use
-autoreleasemessage - sends
-releaseat some point in future (delayed) - used in class convenience methods for temporary objects
- if
+allocor-retain, must-release - if used convenience method, must
-retainto keep
[edit] Example of memory management
comparison of objects
if newName != name, retain newName, release name, and name=newName (returned)
dealloc function - lets you release stuff within class
[edit] Setter/Getter Pattern
- simple but repetitive
- must create code for each getter/setter
[edit] Properties
- quickly and easily create set/get pairs
- specify storage semantics
- easy to override
@property(readwrite) float speed; - attributes, type, name
- attributes
- readonly/readwrite (mutability)
- assign/retain/copy (memory management)
- nonatomic (concurrency)
- setter= / getter= (API for setter/getter names, ex: bool getter -> isGoingFast)
readwrite is default for @property
@synthesize age, parents;
can create custom/overridden methods
[edit] Objective-C Categories
- mix in custom behaviour
- seamlessly add methods to existing classes
- should use subclass instead to add storage or modify behaviour
uses @implementation, could, for example, add a method to NSString
[edit] Objective-C Protocols
- multiple inheritance via specifications
- way for objects to communicate between each other, identical to Java interfaces
- list of methods, classes can opt-in to conform to protocol by implementing methods and advertising that they comply
uses @protocol MyProtocol
@interface Foo : NSObject <MyProtocol>
used in UITableView for datasourcing
[edit] Cocoa Touch
- two pieces of framework
- UIKit - event handling, graphics and windowing, text and web management
- Foundation - object wrappers, strings, data structures, networking and other system services
[edit] Foundation
[edit] Strings
NSString *myString = @"This is a String";
- supports sprintf formatting
- convenience methods in NSString and most of Foundation API - single line stuff like pathComponents (creates array out of /path/to/file), lastPathComponent, stringWithContentsOfFile, etc.
- if you spend 30 lines of code doing something simple, probably missed something!
[edit] Arrays
[edit] Mutable arrays
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1]; [arr addObject:@"randomString"];
[edit] Immutable arrays
NSArray *arr = [NSArray arrayWithObjects:@"foo", @"bar", @"moof", nil]; // nil required at end! tells where array ends
- convenience methods, like componentsJoinedByString
[edit] Dictionaries (aka hashtables in other frameworks)
- also come in immutable/mutables
- array with keys, essentially
-
NSDictionary/NSMutableDictionary
[edit] File I/O
- NSFileManager class handles lots of this stuff
- tmp directory created in root of sandbox, periodically cleared by iPhone
- Library/Caches - saved, not backed up (speeds up sync!!!) - use for non-critical data you don't want to re-download each time
- EVERYTHING ELSE IS BACKED UP
[edit] NSLog
- outputs debug information to debugger console
- supports printf formatting
- also accepts object arguments easily -
NSLog(@"Got an array: %@", myArray);(uses description method for pretty format)
[edit] Bundles
- special type of folder
- your application is an example of one
- executables, nib files (user interface), metadata
- accessible via
NSBundleclass, gives access to static resources (default data, images, sounds) - application bundle is READ ONLY, new data goes in the sandbox instead
- example: pull a default sqlite database if no user data
[edit] Networking
- standard sockets programming
-
CFNetwork,CFSocket(CF = Core Foundation) - POSIX APIs as well
-
NSURLConnectionfor async requests -
NSXML- xml parser - Bonjour networking (zero config discovery of peers on same network)
[edit] UIKit
- visual components
- can have third-party ones
- Image views - scaling! resize, aspect ratio, centring, etc.
- Web views
[edit] Application Design Patterns
[edit] MVC
- Model - Foundation API
- View - UIKit Views
- Controller - UIKit View Controllers
[edit] Target-action
- Control has a target and an action
- Target -> Object
- Action -> Selector
- ex. tap button, sends action to target
[edit] Notifications
- Notification centre - looks for observers to send to
- Observer / controller
- movie player, as example, has 'finished loading', 'finished playing' notifications
-
NSNotificationCenter
[edit] Delegation
- default image is displayed
- instantiate
UIApplication- load main nib
- load main window
- create instance of application delegate
- UI config
- first and last chance to act
- custom class written by you
- conforms to
UIApplicationDelegate - hooked up in interface builder
- two key methods to delegation
-
applicationDidFinishLaaunching- load initial UI, saved state -
applicationWillTerminate- save state and data- just a courtesy - DO NOT ASSUME YOU HAVE A LOT OF TIME! quick and easy stuff, important data should be at time of user-entry
-

