SlideShare a Scribd company logo
CS193p
                           Spring 2010




Wednesday, April 7, 2010
Announcements
                 Get your Axess situation right.

                 If you have not turned in homework, e-mail us.
                 As they say in Air Traffic Control: state your intentions.


                 Homework
                 Any questions about the homework?




Wednesday, April 7, 2010
Communication

                           E-mail
                           Questions are best sent to cs193p@cs.stanford.edu
                           Sending directly to instructor or TA’s risks slow response.


                           Web Site
                           Very Important!
                           http://cs193p.stanford.edu
                           All lectures, assignments, code, etc. will be there.
                           This site will be your best friend when it comes to getting info.




Wednesday, April 7, 2010
Today’s Topics
                           Foundation Framework
                           NSArray, NSDictionary, NSSet
                           NSUserDefaults, etc.

                           Objective-C
                           Protocols and Delegates


                           Memory Management
                           Allocating and initializing objects
                           Reference Counting

                           Demo!




Wednesday, April 7, 2010
NSArray
                      NSArray
                      Ordered collection of objects
                      Cannot be modified once created
                      Important methods:
                      - (int)count
                      - (id)objectAtIndex:(int)index
                      - (void)makeObjectsPerformSelector:(SEL)aSelector
                      - (NSArray *)sortedArrayUsingSelector:(SEL)aSelector


                      NSMutableArray
                      Modifiable version of NSArray
                      - (void)addObject:(id)object
                      - (void)insertObject:(id)object atIndex:(int)index
                      - (void)removeObjectAtIndex:(int)index
                      - (void)replaceObjectAtIndex:(int)index withObject:(id)object




Wednesday, April 7, 2010
NSDictionary
                      NSDictionary
                      Cannot be modified once created!
                      Look up a value using a key (aka a “hash table”)
                      A key must implement - (NSUInteger)hash and - (BOOL)isEqual:(NSObject *)obj
                      Usually keys are NSString objects (since that implements those two)
                      Important methods:
                      - (int)count
                      - (id)objectForKey:(id)key
                      - (NSArray *)allKeys
                      - (NSArray *)allValues


                      NSMutableDictionary
                      Modifiable version of NSDictionary
                      - (void)setObject:(id)object forKey:(id)key
                      - (void)removeObjectForKey:(id)key
                      - (void)addEntriesFromDictionary:(NSDictionary *)dictionary




Wednesday, April 7, 2010
NSSet
                      NSSet
                      Unordered collection of objects without duplicates
                      Cannot be modified once created
                      Important methods:
                      - (int)count
                      - (BOOL)containsObject:(id)object
                      - (id)anyObject
                      - (void)makeObjectsPerformSelector:(SEL)aSelector
                      - (id)member:(id)object (uses isEqual: and returns a matching object)


                      NSMutableSet
                      Modifiable version of NSSet
                      - (void)addObject:(id)object
                      - (void)removeObject:(id)object
                      - (void)unionSet:(NSSet *)otherSet
                      - (void)minusSet:(NSSet *)otherSet
                      - (void)intersectSet:(NSSet *)otherSet


Wednesday, April 7, 2010
Enumeration
                       NSArray of NSString objects

                       NSArray *myArray = ...; / known to only have NSString objects inside
                                                /
                       for (NSString *string in myArray) {
                               double value = [string doubleValue]; / crash if not NSString
                                                                     /
                       }

                       NSArray of id

                       NSArray *myArray = ...; / no idea what kind of objects are inside
                                                /
                       for (id obj in myArray) {
                            < do something with obj here, but make sure you don’t
                              send it a message it doesn’t respond to >
                           if ([obj isKindOfClass:[NSString class]]) {
                                  / send NSString messages to obj with impunity!
                                   /
                           }
                       }


Wednesday, April 7, 2010
Enumeration
                       NSDictionary’s keys

                       NSDictionary *myDict = ...;
                       for (id key in [myDict allKeys]) {
                           < do something with the key >
                       }


                       NSDictionary’s values

                       NSDictionary *myDict = ...;
                       for (id value in [myDict allValues]) {
                           < do something with the value >
                       }




Wednesday, April 7, 2010
Property Lists
                       The term “Property List” just means “one of the
                       collection classes which contains only more collection
                       classes (nothing else).”
                       NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData


                       So an NSArray is a Property List as long as all the
                       objects in it are also Property Lists.

                       An NSDictionary is a Property List as long as all the
                       keys and all the values are Property Lists.

                       Why make this distinction? The SDK has a number of
                       methods here and there which read/write Property Lists.



Wednesday, April 7, 2010
Other Foundation
                       NSUserDefaults
                       - (void)setDouble:(double)aDouble forKey:(NSString *)key
                       - (NSInteger)integerForKey:(NSString *)key
                       - (void)setObject:(id)obj forKey:(NSString *)key
                           (obj must be a Property List)

                       - (NSArray *)arrayForKey:(NSString *)key
                           (if the object stored for that key is not an NSArray, this returns nil)

                       - (void)synchronize / writes to permanent storage
                                            /


                       NSNotification
                       NSTimer
                       NSThread
                       NSFileManager
                       Undo Manager


Wednesday, April 7, 2010
Protocols
                      Very similar to @interface, but no implementation

                      @protocol Foo
                      - (void)doSomething;
                      @optional
                      - (int)getSomething;
                      @required
                      - (NSArray *)getManySomethings:(int)howMany;
                      @end


                      Classes then proclaim they implement a protocol
                      @interface MyClass : NSObject <Foo>
                             ...
                      @end




Wednesday, April 7, 2010
Protocols
                    Declaring arguments to require a protocol
                    - (void)giveMeTheObject:(id <Foo>)anObjectImplementingFoo


                    Declaring variables to require a protocol
                    id <Foo> obj = [[MyClass alloc] init];
                    [obj doSomething]; / will not warn (and should be okay)
                                        /


                    Compiler will warn of misbehavior
                    Class says it implements protocol Foo, but doesn’t implement required methods
                    Assigning an object which does not implement Foo to a variable like obj above
                    Passing an object which does not implement Foo through an argument
                    which requires it (like above)




Wednesday, April 7, 2010
Delegate
                      Very common in SDK to have a property which is a “delegate”

                      Used to pass off responsibility to another object

                      The property will be declared (approximately) like this ...
                      @property id <MyClassDelegate> delegate;


                      Convenient for maintaining MVC boundaries but
                      still have documented interfaces between things
                      For example, the UITableView delegates both the provision of the data
                      and the content of what is drawn to other objects while implementing
                      the core of the user interaction itself




Wednesday, April 7, 2010
Creating Objects
                      Allocating and initializing
                      Send + (id)alloc to the class
                      Send appropriate initializer to what you get back
                      alloc allocates space for the instance variables
                      Default initializer (for NSObject and subclasses) is
                      - (id) init
                      NSObject’ init sets all instance variables to zero
                              s
                      Subclasses of NSObject might define new
                      initializers with more arguments
                      Initializers with fewer args should call those with more args (usually)

                      CalculatorBrain *brain = [[CalculatorBrain alloc] init];

                      UIView *view = [[UIView alloc] initWithFrame:aRect];
                      UIView *view = [[UIView alloc] init]; / some default frame
                                                             /

                      MyClass *obj = [MyClass alloc];       / ack! no init! don’t do this!
                                                             /

Wednesday, April 7, 2010
Creating Objects
                       Goofy implementation of initializers
                           #import <UIKit/UIKit.h>                 initWithFrame: is UIView’s “designated initializer”
                                                                       so we, as a subclass, must call it in our DI.
                                                                       We don’t have to override it, but we should
                           @implementation MyView                    if it makes any sense whatsoever to our class.


                           - (id)initWithFrame:(CGRect)aRect
                           {
                                  if (self = [super initWithFrame:aRect]) {
                                      / initialize my class here
                                       /
                                  }
                                  return self;
                           }


                           @end


Wednesday, April 7, 2010
Creating Objects
                 Asking other objects to create an object for you
                   NSString *s = [otherString stringByAppendingString:@”hi”];
                   NSArray *keys = [dictionary allKeys];
                   NSString *lowerString = [string lowercaseString];
                   NSNumber *n = [NSNumber numberWithFloat:9.0];
                   NSDate *date = [NSDate date]; / returns the date/time now
                                                  /




Wednesday, April 7, 2010
Memory Management
                   When does the memory get freed?

                   Garbage Collection!

                   NO, sorry.

                   Reference Counting




Wednesday, April 7, 2010
Reference Counting
                   Objects take ownership for other objects.

                   Multiple owners is okay.

                   Mechanism for taking “temporary” ownership.

                   When last object gives up ownership, deallocate.




Wednesday, April 7, 2010
Object Ownership
                      When you call alloc, you take ownership.

                      When you ask another object to create an object for you,
                      you are not taking ownership (with a couple of exceptions).

                      But if you want to access that object outside the
                      method you are in, you must take ownership.

                      You take ownership by sending the object you
                      want to own the message “retain.”

                      When you are done owning the object, send it “release.”
                      If you are the last owner, object will be freed.
                      Messages sent to that object after that will crash your application.



Wednesday, April 7, 2010
autorelease
                      What if you want to give an object to someone?
                      Usually you are doing this by returning it from one of your methods.


                      Before you return it to them, send the object
                      the message “autorelease” first.

                      UIKit will automatically send it release at some
                      later time (but not until call stack unwinds).
                      We’ll talk more about how this works when we get to threads.


                      All those NSString, NSArray, etc. methods are
                      returning “autoreleased” objects.


Wednesday, April 7, 2010
autorelease
                      Example

                 - (Money *)showMeTheMoney:(double)amount
                 {
                      Money *theMoney = [[Money alloc] init:amount];
                           [theMoney autorelease];
                           return theMoney;
                 }




Wednesday, April 7, 2010
autorelease
                      Example

                 - (Money *)showMeTheMoney:(double)amount
                 {
                      Money *theMoney = [[Money alloc] init:amount];


                           return [theMoney autorelease];
                 }




Wednesday, April 7, 2010
autorelease
                      Mutable collection class autorelease creators
                      [NSMutableString string];
                      [NSMutableArray array];
                      [NSMutableDictionary dictionary];


                      Create them, load them up, and return them
                       - (NSString *)showMeTheMoney:(double)amount
                       {
                            NSMutableString *s = [NSMutableString string];
                               [s appendString:@”The Money:“];
                               [s appendFormat:@” %g“, amount];
                               return s;
                           }
                                               Note there is no autorelease here!


Wednesday, April 7, 2010
autorelease
                    Immutable “with” creators
                    [NSString stringWith... ];
                    [NSArray arrayWith... ];
                    [NSDictionary dictionaryWith...];


                    [NSString stringWithFormat:@”%@ %d”, ...];
                    [NSArray arrayWithObjects:obj1, obj2, nil];
                    [NSDictionary dictionaryWithObjectsAndKeys:...];
                    [NSArray arrayWithContentsOfFile:(NSString *)path];
                    [NSDictionary dictionaryWithContentsOfFile:...];
                    [NSString stringWithContentsOfFile:encoding:error:];




Wednesday, April 7, 2010
Other Ownership Rules
                      When you put an object in an NSArray or
                      NSDictionary, they do take ownership. When
                      you take an object out, they release ownership.

                      You also implicitly retain if you copy an object
                      This is done using the copy method.


                      Methods whose names start with
                      alloc, copy or new return an object you own
                      So you must release it at some point down the road


                      You should release an object as soon as possible
                      That is to say, the instant you are done with it.


Wednesday, April 7, 2010
Deallocation
                      What happens when the last owner releases?

                      A special method, - (void)dealloc, is called.

                      You should override this method and release
                      any instance variables you own.

                      And then be sure to call [super dealloc] to
                      let your superclass release it’s owned objects.

                      NEVER call dealloc. It is called automatically
                      when the last owner releases.


Wednesday, April 7, 2010
Properties
                Remember @property?

                Does the @synthesized getter method
                return autoreleased object?

                NO! That getter is returning an instance variable.
                If the caller doesn’t retain it, then when your
                object is deallocated, that caller will have a bad
                pointer (assuming you properly releases your
                instance variables in your dealloc).




Wednesday, April 7, 2010
Properties
                Remember @property?

                Does the @synthesized setter do a retain when
                it is called?

                You get to decide:
                   @property (retain) NSString *name;

                   @synthesize will create a setter equivalent to this ...

                   - (void)setName:(NSString *)aString
                   {
                       [name release];
                       name = [aString retain];
                   }


Wednesday, April 7, 2010
Properties
                Remember @property?

                Does the @synthesized setter do a retain when
                it is called?

                You get to decide:
                   @property (copy) NSString *name;

                   @synthesize will create a setter equivalent to this ...

                   - (void)setName:(NSString *)aString
                   {
                       [name release];
                       name = [aString copy];
                   }


Wednesday, April 7, 2010
Properties
                Remember @property?

                Does the @synthesized setter do a retain when
                it is called?

                You get to decide:
                   @property (assign) NSString *name;

                   @synthesize will create a setter equivalent to this ...

                   - (void)setName:(NSString *)aString
                   {
                       name = aString;
                   }



Wednesday, April 7, 2010
Wake up!
                   What about objects that come out of nib files?

                   They are archived in IB, then unarchived in your running app.

                   So where do you initialize if not in init?
                   - (void)awakeFromNib    / override this NSObject method
                                            /
                   - (void)viewDidLoad     / only for UIViewController subclasses
                                            /




Wednesday, April 7, 2010
viewDidUnload
                   And what about release-ing IBOutlets in UIViewControllers?

                   Don’t do it in dealloc because your controller’s views are
                   allowed to be “unloaded” to save memory when not on-screen.
                   Create @properties (retain) for all of them and then set them
                   to nil in the method viewDidUnload ...
                   @property (retain, nonatomic) IBOutlet UILabel *myOutlet;

                   - (void)viewDidUnload
                   {
                       self.myOutlet = nil;   / this will release because property is retain
                                               /
                       [super viewDidUnload]; / probably not necessary unless you think it is
                                               /
                   }

                   When/if the view is reloaded, your outlets will get hooked
                   back up and - (void)viewDidLoad will get called (again).


Wednesday, April 7, 2010
Demo
                 MVC: Collector

                 NSArray, NSDictionary

                 Instrospection

                 @property

                 Memory Management




Wednesday, April 7, 2010
Homework
                 Make your CalculatorBrain support variables

                 Mostly NSArray, NSDictionary work

                 Some Instrospection

                 Get Memory Management right!
                 Not too difficult, but a new concept. Be diligent!




Wednesday, April 7, 2010
Next Week
                 Custom Views, Navigation Controllers




Wednesday, April 7, 2010

More Related Content

What's hot

みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
techtalkdwango
 
C Language Unit-7
C Language Unit-7C Language Unit-7
C Language Unit-7
kasaragadda srinivasrao
 
iPhone Memory Management
iPhone Memory ManagementiPhone Memory Management
iPhone Memory Management
Vadim Zimin
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
Data perisistence in iOS
Data perisistence in iOSData perisistence in iOS
Data perisistence in iOS
mobiledeveloperpl
 
Unit7 jwfiles
Unit7 jwfilesUnit7 jwfiles
Unit7 jwfiles
mrecedu
 
XSLT 1 and XPath Quick Reference (from mulberrytech.com)
XSLT 1 and XPath Quick Reference (from mulberrytech.com)XSLT 1 and XPath Quick Reference (from mulberrytech.com)
XSLT 1 and XPath Quick Reference (from mulberrytech.com)
FrescatiStory
 
ActiveSupport
ActiveSupportActiveSupport
ActiveSupport
Kevin Faustino
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
Hussain Behestee
 
7494609
74946097494609
Blockchain - a simple implementation
Blockchain - a simple implementationBlockchain - a simple implementation
Blockchain - a simple implementation
Commit Software Sh.p.k.
 
Encontra presentation
Encontra presentationEncontra presentation
Encontra presentation
Ricardo Dias
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
Mark Baker
 
Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩
HyeonSeok Choi
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
Easy undo.key
Easy undo.keyEasy undo.key
Easy undo.key
zachwaugh
 
RaleighFS v5
RaleighFS v5RaleighFS v5
RaleighFS v5
Matteo Bertozzi
 
this is ruby test
this is ruby testthis is ruby test
this is ruby test
51 lecture
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
Jai Santhosh
 
Using Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer ArchitectureUsing Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer Architecture
Garann Means
 

What's hot (20)

みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 
C Language Unit-7
C Language Unit-7C Language Unit-7
C Language Unit-7
 
iPhone Memory Management
iPhone Memory ManagementiPhone Memory Management
iPhone Memory Management
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
 
Data perisistence in iOS
Data perisistence in iOSData perisistence in iOS
Data perisistence in iOS
 
Unit7 jwfiles
Unit7 jwfilesUnit7 jwfiles
Unit7 jwfiles
 
XSLT 1 and XPath Quick Reference (from mulberrytech.com)
XSLT 1 and XPath Quick Reference (from mulberrytech.com)XSLT 1 and XPath Quick Reference (from mulberrytech.com)
XSLT 1 and XPath Quick Reference (from mulberrytech.com)
 
ActiveSupport
ActiveSupportActiveSupport
ActiveSupport
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
7494609
74946097494609
7494609
 
Blockchain - a simple implementation
Blockchain - a simple implementationBlockchain - a simple implementation
Blockchain - a simple implementation
 
Encontra presentation
Encontra presentationEncontra presentation
Encontra presentation
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
 
Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Easy undo.key
Easy undo.keyEasy undo.key
Easy undo.key
 
RaleighFS v5
RaleighFS v5RaleighFS v5
RaleighFS v5
 
this is ruby test
this is ruby testthis is ruby test
this is ruby test
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
 
Using Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer ArchitectureUsing Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer Architecture
 

Similar to Lecture 04

Introduction to Objective C
Introduction to Objective CIntroduction to Objective C
Introduction to Objective C
Hassan Aftab
 
{"JSON, Swift and Type Safety" : "It's a wrap"}
{"JSON, Swift and Type Safety" : "It's a wrap"}{"JSON, Swift and Type Safety" : "It's a wrap"}
{"JSON, Swift and Type Safety" : "It's a wrap"}
Anthony Levings
 
iOS Development with RubyMotion
iOS Development with RubyMotioniOS Development with RubyMotion
iOS Development with RubyMotion
Invisiblelines
 
Data perisistance i_os
Data perisistance i_osData perisistance i_os
Data perisistance i_os
Michał Tuszyński
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
Jung Kim
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
Giovanni Lodi
 
09 Data
09 Data09 Data
09 Data
Mahmoud
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
Globalidiots
 
iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storage
Jussi Pohjolainen
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
Joris Verbogt
 
numpy.pdf
numpy.pdfnumpy.pdf
numpy.pdf
ssuser457188
 
For mobile 5/13'
For mobile 5/13'For mobile 5/13'
For mobile 5/13'
Jakub Hladík
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
Janet Huang
 
Introduction To Core Data
Introduction To Core DataIntroduction To Core Data
Introduction To Core Data
danielctull
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
Chris Mar
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
SV.CO
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
Massimo Oliviero
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
hardjasonoco14599
 
Learn Ruby by Reading the Source
Learn Ruby by Reading the SourceLearn Ruby by Reading the Source
Learn Ruby by Reading the Source
Burke Libbey
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
Prajwala Manchikatla
 

Similar to Lecture 04 (20)

Introduction to Objective C
Introduction to Objective CIntroduction to Objective C
Introduction to Objective C
 
{"JSON, Swift and Type Safety" : "It's a wrap"}
{"JSON, Swift and Type Safety" : "It's a wrap"}{"JSON, Swift and Type Safety" : "It's a wrap"}
{"JSON, Swift and Type Safety" : "It's a wrap"}
 
iOS Development with RubyMotion
iOS Development with RubyMotioniOS Development with RubyMotion
iOS Development with RubyMotion
 
Data perisistance i_os
Data perisistance i_osData perisistance i_os
Data perisistance i_os
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
 
09 Data
09 Data09 Data
09 Data
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
 
iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storage
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 
numpy.pdf
numpy.pdfnumpy.pdf
numpy.pdf
 
For mobile 5/13'
For mobile 5/13'For mobile 5/13'
For mobile 5/13'
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Introduction To Core Data
Introduction To Core DataIntroduction To Core Data
Introduction To Core Data
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
 
Learn Ruby by Reading the Source
Learn Ruby by Reading the SourceLearn Ruby by Reading the Source
Learn Ruby by Reading the Source
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 

Lecture 04

  • 1. CS193p Spring 2010 Wednesday, April 7, 2010
  • 2. Announcements Get your Axess situation right. If you have not turned in homework, e-mail us. As they say in Air Traffic Control: state your intentions. Homework Any questions about the homework? Wednesday, April 7, 2010
  • 3. Communication E-mail Questions are best sent to cs193p@cs.stanford.edu Sending directly to instructor or TA’s risks slow response. Web Site Very Important! http://cs193p.stanford.edu All lectures, assignments, code, etc. will be there. This site will be your best friend when it comes to getting info. Wednesday, April 7, 2010
  • 4. Today’s Topics Foundation Framework NSArray, NSDictionary, NSSet NSUserDefaults, etc. Objective-C Protocols and Delegates Memory Management Allocating and initializing objects Reference Counting Demo! Wednesday, April 7, 2010
  • 5. NSArray NSArray Ordered collection of objects Cannot be modified once created Important methods: - (int)count - (id)objectAtIndex:(int)index - (void)makeObjectsPerformSelector:(SEL)aSelector - (NSArray *)sortedArrayUsingSelector:(SEL)aSelector NSMutableArray Modifiable version of NSArray - (void)addObject:(id)object - (void)insertObject:(id)object atIndex:(int)index - (void)removeObjectAtIndex:(int)index - (void)replaceObjectAtIndex:(int)index withObject:(id)object Wednesday, April 7, 2010
  • 6. NSDictionary NSDictionary Cannot be modified once created! Look up a value using a key (aka a “hash table”) A key must implement - (NSUInteger)hash and - (BOOL)isEqual:(NSObject *)obj Usually keys are NSString objects (since that implements those two) Important methods: - (int)count - (id)objectForKey:(id)key - (NSArray *)allKeys - (NSArray *)allValues NSMutableDictionary Modifiable version of NSDictionary - (void)setObject:(id)object forKey:(id)key - (void)removeObjectForKey:(id)key - (void)addEntriesFromDictionary:(NSDictionary *)dictionary Wednesday, April 7, 2010
  • 7. NSSet NSSet Unordered collection of objects without duplicates Cannot be modified once created Important methods: - (int)count - (BOOL)containsObject:(id)object - (id)anyObject - (void)makeObjectsPerformSelector:(SEL)aSelector - (id)member:(id)object (uses isEqual: and returns a matching object) NSMutableSet Modifiable version of NSSet - (void)addObject:(id)object - (void)removeObject:(id)object - (void)unionSet:(NSSet *)otherSet - (void)minusSet:(NSSet *)otherSet - (void)intersectSet:(NSSet *)otherSet Wednesday, April 7, 2010
  • 8. Enumeration NSArray of NSString objects NSArray *myArray = ...; / known to only have NSString objects inside / for (NSString *string in myArray) { double value = [string doubleValue]; / crash if not NSString / } NSArray of id NSArray *myArray = ...; / no idea what kind of objects are inside / for (id obj in myArray) { < do something with obj here, but make sure you don’t send it a message it doesn’t respond to > if ([obj isKindOfClass:[NSString class]]) { / send NSString messages to obj with impunity! / } } Wednesday, April 7, 2010
  • 9. Enumeration NSDictionary’s keys NSDictionary *myDict = ...; for (id key in [myDict allKeys]) { < do something with the key > } NSDictionary’s values NSDictionary *myDict = ...; for (id value in [myDict allValues]) { < do something with the value > } Wednesday, April 7, 2010
  • 10. Property Lists The term “Property List” just means “one of the collection classes which contains only more collection classes (nothing else).” NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData So an NSArray is a Property List as long as all the objects in it are also Property Lists. An NSDictionary is a Property List as long as all the keys and all the values are Property Lists. Why make this distinction? The SDK has a number of methods here and there which read/write Property Lists. Wednesday, April 7, 2010
  • 11. Other Foundation NSUserDefaults - (void)setDouble:(double)aDouble forKey:(NSString *)key - (NSInteger)integerForKey:(NSString *)key - (void)setObject:(id)obj forKey:(NSString *)key (obj must be a Property List) - (NSArray *)arrayForKey:(NSString *)key (if the object stored for that key is not an NSArray, this returns nil) - (void)synchronize / writes to permanent storage / NSNotification NSTimer NSThread NSFileManager Undo Manager Wednesday, April 7, 2010
  • 12. Protocols Very similar to @interface, but no implementation @protocol Foo - (void)doSomething; @optional - (int)getSomething; @required - (NSArray *)getManySomethings:(int)howMany; @end Classes then proclaim they implement a protocol @interface MyClass : NSObject <Foo> ... @end Wednesday, April 7, 2010
  • 13. Protocols Declaring arguments to require a protocol - (void)giveMeTheObject:(id <Foo>)anObjectImplementingFoo Declaring variables to require a protocol id <Foo> obj = [[MyClass alloc] init]; [obj doSomething]; / will not warn (and should be okay) / Compiler will warn of misbehavior Class says it implements protocol Foo, but doesn’t implement required methods Assigning an object which does not implement Foo to a variable like obj above Passing an object which does not implement Foo through an argument which requires it (like above) Wednesday, April 7, 2010
  • 14. Delegate Very common in SDK to have a property which is a “delegate” Used to pass off responsibility to another object The property will be declared (approximately) like this ... @property id <MyClassDelegate> delegate; Convenient for maintaining MVC boundaries but still have documented interfaces between things For example, the UITableView delegates both the provision of the data and the content of what is drawn to other objects while implementing the core of the user interaction itself Wednesday, April 7, 2010
  • 15. Creating Objects Allocating and initializing Send + (id)alloc to the class Send appropriate initializer to what you get back alloc allocates space for the instance variables Default initializer (for NSObject and subclasses) is - (id) init NSObject’ init sets all instance variables to zero s Subclasses of NSObject might define new initializers with more arguments Initializers with fewer args should call those with more args (usually) CalculatorBrain *brain = [[CalculatorBrain alloc] init]; UIView *view = [[UIView alloc] initWithFrame:aRect]; UIView *view = [[UIView alloc] init]; / some default frame / MyClass *obj = [MyClass alloc]; / ack! no init! don’t do this! / Wednesday, April 7, 2010
  • 16. Creating Objects Goofy implementation of initializers #import <UIKit/UIKit.h> initWithFrame: is UIView’s “designated initializer” so we, as a subclass, must call it in our DI. We don’t have to override it, but we should @implementation MyView if it makes any sense whatsoever to our class. - (id)initWithFrame:(CGRect)aRect { if (self = [super initWithFrame:aRect]) { / initialize my class here / } return self; } @end Wednesday, April 7, 2010
  • 17. Creating Objects Asking other objects to create an object for you NSString *s = [otherString stringByAppendingString:@”hi”]; NSArray *keys = [dictionary allKeys]; NSString *lowerString = [string lowercaseString]; NSNumber *n = [NSNumber numberWithFloat:9.0]; NSDate *date = [NSDate date]; / returns the date/time now / Wednesday, April 7, 2010
  • 18. Memory Management When does the memory get freed? Garbage Collection! NO, sorry. Reference Counting Wednesday, April 7, 2010
  • 19. Reference Counting Objects take ownership for other objects. Multiple owners is okay. Mechanism for taking “temporary” ownership. When last object gives up ownership, deallocate. Wednesday, April 7, 2010
  • 20. Object Ownership When you call alloc, you take ownership. When you ask another object to create an object for you, you are not taking ownership (with a couple of exceptions). But if you want to access that object outside the method you are in, you must take ownership. You take ownership by sending the object you want to own the message “retain.” When you are done owning the object, send it “release.” If you are the last owner, object will be freed. Messages sent to that object after that will crash your application. Wednesday, April 7, 2010
  • 21. autorelease What if you want to give an object to someone? Usually you are doing this by returning it from one of your methods. Before you return it to them, send the object the message “autorelease” first. UIKit will automatically send it release at some later time (but not until call stack unwinds). We’ll talk more about how this works when we get to threads. All those NSString, NSArray, etc. methods are returning “autoreleased” objects. Wednesday, April 7, 2010
  • 22. autorelease Example - (Money *)showMeTheMoney:(double)amount { Money *theMoney = [[Money alloc] init:amount]; [theMoney autorelease]; return theMoney; } Wednesday, April 7, 2010
  • 23. autorelease Example - (Money *)showMeTheMoney:(double)amount { Money *theMoney = [[Money alloc] init:amount]; return [theMoney autorelease]; } Wednesday, April 7, 2010
  • 24. autorelease Mutable collection class autorelease creators [NSMutableString string]; [NSMutableArray array]; [NSMutableDictionary dictionary]; Create them, load them up, and return them - (NSString *)showMeTheMoney:(double)amount { NSMutableString *s = [NSMutableString string]; [s appendString:@”The Money:“]; [s appendFormat:@” %g“, amount]; return s; } Note there is no autorelease here! Wednesday, April 7, 2010
  • 25. autorelease Immutable “with” creators [NSString stringWith... ]; [NSArray arrayWith... ]; [NSDictionary dictionaryWith...]; [NSString stringWithFormat:@”%@ %d”, ...]; [NSArray arrayWithObjects:obj1, obj2, nil]; [NSDictionary dictionaryWithObjectsAndKeys:...]; [NSArray arrayWithContentsOfFile:(NSString *)path]; [NSDictionary dictionaryWithContentsOfFile:...]; [NSString stringWithContentsOfFile:encoding:error:]; Wednesday, April 7, 2010
  • 26. Other Ownership Rules When you put an object in an NSArray or NSDictionary, they do take ownership. When you take an object out, they release ownership. You also implicitly retain if you copy an object This is done using the copy method. Methods whose names start with alloc, copy or new return an object you own So you must release it at some point down the road You should release an object as soon as possible That is to say, the instant you are done with it. Wednesday, April 7, 2010
  • 27. Deallocation What happens when the last owner releases? A special method, - (void)dealloc, is called. You should override this method and release any instance variables you own. And then be sure to call [super dealloc] to let your superclass release it’s owned objects. NEVER call dealloc. It is called automatically when the last owner releases. Wednesday, April 7, 2010
  • 28. Properties Remember @property? Does the @synthesized getter method return autoreleased object? NO! That getter is returning an instance variable. If the caller doesn’t retain it, then when your object is deallocated, that caller will have a bad pointer (assuming you properly releases your instance variables in your dealloc). Wednesday, April 7, 2010
  • 29. Properties Remember @property? Does the @synthesized setter do a retain when it is called? You get to decide: @property (retain) NSString *name; @synthesize will create a setter equivalent to this ... - (void)setName:(NSString *)aString { [name release]; name = [aString retain]; } Wednesday, April 7, 2010
  • 30. Properties Remember @property? Does the @synthesized setter do a retain when it is called? You get to decide: @property (copy) NSString *name; @synthesize will create a setter equivalent to this ... - (void)setName:(NSString *)aString { [name release]; name = [aString copy]; } Wednesday, April 7, 2010
  • 31. Properties Remember @property? Does the @synthesized setter do a retain when it is called? You get to decide: @property (assign) NSString *name; @synthesize will create a setter equivalent to this ... - (void)setName:(NSString *)aString { name = aString; } Wednesday, April 7, 2010
  • 32. Wake up! What about objects that come out of nib files? They are archived in IB, then unarchived in your running app. So where do you initialize if not in init? - (void)awakeFromNib / override this NSObject method / - (void)viewDidLoad / only for UIViewController subclasses / Wednesday, April 7, 2010
  • 33. viewDidUnload And what about release-ing IBOutlets in UIViewControllers? Don’t do it in dealloc because your controller’s views are allowed to be “unloaded” to save memory when not on-screen. Create @properties (retain) for all of them and then set them to nil in the method viewDidUnload ... @property (retain, nonatomic) IBOutlet UILabel *myOutlet; - (void)viewDidUnload { self.myOutlet = nil; / this will release because property is retain / [super viewDidUnload]; / probably not necessary unless you think it is / } When/if the view is reloaded, your outlets will get hooked back up and - (void)viewDidLoad will get called (again). Wednesday, April 7, 2010
  • 34. Demo MVC: Collector NSArray, NSDictionary Instrospection @property Memory Management Wednesday, April 7, 2010
  • 35. Homework Make your CalculatorBrain support variables Mostly NSArray, NSDictionary work Some Instrospection Get Memory Management right! Not too difficult, but a new concept. Be diligent! Wednesday, April 7, 2010
  • 36. Next Week Custom Views, Navigation Controllers Wednesday, April 7, 2010