Lecture 3 Slides (January 12, 2010)

Similar documents
西川町広報誌NETWORKにしかわ2011年1月号

fx-9860G Manager PLUS_J

3

C. S2 X D. E.. (1) X S1 10 S2 X+S1 3 X+S S1S2 X+S1+S2 X S1 X+S S X+S2 X A. S1 2 a. b. c. d. e. 2


Introduction Purpose This training course describes the configuration and session features of the High-performance Embedded Workshop (HEW), a key tool

What s your name? Help me carry the baggage, please. politeness What s your name? Help me carry the baggage, please. iii

国際恋愛で避けるべき7つの失敗と解決策


Microsoft Word - Win-Outlook.docx

S1Šû‘KŒâ‚è

-2-

Introduction Purpose This training course demonstrates the use of the High-performance Embedded Workshop (HEW), a key tool for developing software for

Ver.1 1/17/2003 2

P

L1 What Can You Blood Type Tell Us? Part 1 Can you guess/ my blood type? Well,/ you re very serious person/ so/ I think/ your blood type is A. Wow!/ G


はじめに

生研ニュースNo.132

NO

open / window / I / shall / the? something / want / drink / I / to the way / you / tell / the library / would / to / me

平成29年度英語力調査結果(中学3年生)の概要

きずなプロジェクト-表紙.indd

elemmay09.pub

高2SL高1HL 文法後期後半_テキスト-0108.indd

日本語教育紀要 7/pdf用 表紙

,,,,., C Java,,.,,.,., ,,.,, i


Introduction Purpose The course describes library configuration and usage in the High Performance Embedded Workshop (HEW), which speeds development of

CONTENTS Public relations brochure of Higashikawa March No.749 2

28 Docker Design and Implementation of Program Evaluation System Using Docker Virtualized Environment



AERA_English_CP_Sample_org.pdf

AN 100: ISPを使用するためのガイドライン

P

鹿大広報149号

1 # include < stdio.h> 2 # include < string.h> 3 4 int main (){ 5 char str [222]; 6 scanf ("%s", str ); 7 int n= strlen ( str ); 8 for ( int i=n -2; i

Answers Practice 08 JFD1

2


™…

第17回勉強会「英語の教え方教室」報告


178 New Horizon English Course 28 : NH 3 1. NH 1 p ALT HP NH 2 Unit 2 p. 18 : Hi, Deepa. What are your plans for the holidays? I m going to visi

取説_KX-PW38CL_PW48CL

25 II :30 16:00 (1),. Do not open this problem booklet until the start of the examination is announced. (2) 3.. Answer the following 3 proble


高等学校 英語科


05[ ]櫻井・小川(責)岩.indd

GOT7 EYES ON YOU ミニアルバム 1. ノハナマン What? I think it s stuck ノマンイッスミョンデェヌンゴヤ Yeah モドゥンゴルジュゴシポソ Yo baby ノワオディトゥンジカゴシポ everywhere ナンニガウォナンダミョンジュゴシポ anythin

1 ( 8:12) Eccles. 1:8 2 2

Read the following text messages. Study the names carefully. 次のメッセージを読みましょう 名前をしっかり覚えましょう Dear Jenny, Iʼm Kim Garcia. Iʼm your new classmate. These ar



137. Tenancy specific information (a) Amount of deposit paid. (insert amount of deposit paid; in the case of a joint tenancy it should be the total am

49148

CA HP,,,,,,.,,,,,,.,,,,,,.,,,,,,.,,,,,,.,,,,,,.,,,,,,.,,,,,.,,,,,.,,,,,.,,,,,.,,,,,.,,,,,.,,,,,.,,,,,.,,,,,,.,,,,,.,,,,,,.,,,,,.,,,,,.,,,,,,.,,,,,,.,,

第16回ニュージェネレーション_cs4.indd


sein_sandwich2_FM_bounus_NYUKO.indd

RX600 & RX200シリーズ アプリケーションノート RX用仮想EEPROM

Page 1 of 6 B (The World of Mathematics) November 20, 2006 Final Exam 2006 Division: ID#: Name: 1. p, q, r (Let p, q, r are propositions. ) (10pts) (a


When creating an interactive case scenario of a problem that may occur in the educational field, it becomes especially difficult to assume a clear obj

How to read the marks and remarks used in this parts book. Section 1 : Explanation of Code Use In MRK Column OO : Interchangeable between the new part

How to read the marks and remarks used in this parts book. Section 1 : Explanation of Code Use In MRK Column OO : Interchangeable between the new part

千葉県における温泉地の地域的展開

How to read the marks and remarks used in this parts book. Section 1 : Explanation of Code Use In MRK Column OO : Interchangeable between the new part

David A Thayne Presents. Bonus Edition OK! tossa_h_ol.indd 1 12/12/07 21:09

i5 Catalyst Case Instructions JP

Vol92.indd

untitled

Cain & Abel

目次 1. レッスンで使える表現 レッスンでお困りの際に使えるフレーズからレッスンの中でよく使われるフレーズまで 便利な表現をご紹介させていただきます ご活用方法として 講師に伝えたいことが伝わらない場合に下記の通りご利用ください 1 該当の表現を直接講師に伝える 2 該当の英語表現を Skype

B. Quick Q&A (2-3 minutes) 1. Do you usually read instruction manuals before using something? (e.g. gadgets) 2. Have you tried reading an instruction

\615L\625\761\621\745\615\750\617\743\623\6075\614\616\615\606.PS

How to read the marks and remarks used in this parts book. Section 1 : Explanation of Code Use In MRK Column OO : Interchangeable between the new part

STEP 02 Memo: Self-Introduction Self-Introduction About your family About your school life (your classes, club/juku, and so on.) Questions to your Pen


C H H H C H H H C C CUTION:These telephones are for use in Japan only. They cannot be used in other countries because of differences in voltages, tele


日本版 General Social Surveys 研究論文集[2]

取説_VE-PV11L(応用編)

先端社会研究 ★5★号/4.山崎

,

Kyushu Communication Studies 第2号

/ SCHEDULE /06/07(Tue) / Basic of Programming /06/09(Thu) / Fundamental structures /06/14(Tue) / Memory Management /06/1

Microsoft Word - j201drills27.doc

<4D F736F F F696E74202D CEA8D758DC E396BC8E8C F92758E8C81458C E8C81458F9593AE8E8C>

評論・社会科学 84号(よこ)(P)/3.金子

Bull. of Nippon Sport Sci. Univ. 47 (1) Devising musical expression in teaching methods for elementary music An attempt at shared teaching

J.S

LC304_manual.ai

平成23年度 児童・生徒の学力向上を図るための調査 中学校第2 学年 外国語(英語) 調査票


L3 Japanese (90570) 2008

CONTENTS Public relations brochure of Higashikawa November No.745 Higashikawa 215 November 2

22 1,936, ,115, , , , , , ,

Transcription:

CS193P - Lecture 3 iphone Application Development Custom Classes Object Lifecycle Autorelease Properties 1

Announcements Assignments 1A and 1B due Wednesday 1/13 at 11:59 PM Enrolled Stanford students can email cs193p@cs.stanford.edu with any questions Submit early! Instructions on the website... Delete the build directory manually, Xcode won t do it 2

Announcements Assignments 2A and 2B due Wednesday 1/20 at 11:59 PM 2A: Continuation of Foundation tool Add custom class Basic memory management 2B: Beginning of first iphone application Topics to be covered on Thursday, 1/14 Assignment contains extensive walkthrough 3

Enrolled students & itunes U Lectures have begun showing up on itunes U Lead time is longer than last year Come to class!! Lectures may not post in time for assignments 4

Office Hours Paul s office hours: Thursday 2-4, Gates B26B David s office hours: Mondays 4-6pm: Gates 360 5

Today s Topics Questions from Assignment 1A or 1B? Creating Custom Classes Object Lifecycle Autorelease Objective-C Properties 6

Custom Classes 7

Design Phase Create a class Person Determine the superclass NSObject (in this case) What properties should it have? Name, age, whether they can vote What actions can it perform? Cast a ballot 8

Defining a class A public header and a private implementation Header File Implementation File 9

Defining a class A public header and a private implementation Header File Implementation File 9

Class interface declared in header file #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 10

Defining a class A public header and a private implementation Header File Implementation File 11

Implementing custom class Implement setter/getter methods Implement action methods 12

Class Implementation #import "Person.h" @implementation Person - (int)age { return age; - (void)setage:(int)value { age = value; //... and other methods @end 13

Calling your own methods #import "Person.h" @implementation Person - (BOOL)canLegallyVote { - (void)castballot { @end 14

Calling your own methods #import "Person.h" @implementation Person - (BOOL)canLegallyVote { return ([self age] >= 18); - (void)castballot { @end 14

Calling your own methods #import "Person.h" @implementation Person - (BOOL)canLegallyVote { return ([self age] >= 18); - (void)castballot { if ([self canlegallyvote]) { // do voting stuff else { NSLog (@ I m not allowed to vote! ); @end 14

Superclass methods As we just saw, objects have an implicit variable named self Like this in Java and C++ Can also invoke superclass methods using super - (void)dosomething { // Call superclass implementation first [super dosomething]; // Then do our custom behavior int foo = bar; //... 15

Object Lifecycle 16

Object Lifecycle Creating objects Memory management Destroying objects 17

Object Creation Two step process allocate memory to store the object initialize object state + alloc Class method that knows how much memory is needed - init Instance method to set initial values, perform other setup 18

Create = Allocate + Initialize Person *person = nil; person = [[Person alloc] init]; 19

Implementing your own -init method #import "Person.h" @implementation Person - (id)init { // allow superclass to initialize its state first if (self = [super init]) { age = 0; name = @ Bob ; // do other initialization... return self; @end 20

Multiple init methods Classes may define multiple init methods - (id)init; - (id)initwithname:(nsstring *)name; - (id)initwithname:(nsstring *)name age:(int)age; Less specific ones typically call more specific with default values - (id)init { return [self initwithname:@ No Name ]; - (id)initwithname:(nsstring *)name { return [self initwithname:name age:0]; 21

Finishing Up With an Object Person *person = nil; person = [[Person alloc] init]; [person setname:@ Jimmy Jones ]; [person setage:32]; [person castballot]; [person dosomethingelse]; 22

Finishing Up With an Object Person *person = nil; person = [[Person alloc] init]; [person setname:@ Jimmy Jones ]; [person setage:32]; [person castballot]; [person dosomethingelse]; // What do we do with person when we re done? 22

Memory Management C Objective-C Allocation malloc alloc Destruction free dealloc Calls must be balanced Otherwise your program may leak or crash However, you ll never call -dealloc directly One exception, we ll see in a bit... 23

Reference Counting Every object has a retain count Defined on NSObject As long as retain count is > 0, object is alive and valid +alloc and -copy create objects with retain count == 1 -retain increments retain count -release decrements retain count When retain count reaches 0, object is destroyed -dealloc method invoked automatically One-way street, once you re in -dealloc there s no turning back 24

Balanced Calls Person *person = nil; person = [[Person alloc] init]; [person setname:@ Jimmy Jones ]; [person setage:32]; [person castballot]; [person dosomethingelse]; // When we re done with person, release it [person release]; // person will be destroyed here 25

Reference counting in action Person *person = [[Person alloc] init]; Retain count begins at 1 with +alloc [person retain]; Retain count increases to 2 with -retain [person release]; Retain count decreases to 1 with -release [person release]; Retain count decreases to 0, -dealloc automatically called 26

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated 27

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated [person dosomething]; // Crash! 27

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated 27

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated person = nil; 27

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated person = nil; [person dosomething]; // No effect 27

Implementing a -dealloc method #import "Person.h" @implementation Person - (void)dealloc { // Do any cleanup that s necessary //... // when we re done, call super to clean us up [super dealloc]; @end 28

Object Lifecycle Recap Objects begin with a retain count of 1 Increase and decrease with -retain and -release When retain count reaches 0, object deallocated automatically You never call dealloc explicitly in your code Exception is calling -[super dealloc] You only deal with alloc, copy, retain, release 29

Object Ownership #import <Foundation/Foundation.h> @interface Person : NSObject { // instance variables NSString *name; // Person class owns the name int age; // method declarations - (NSString *)name; - (void)setname:(nsstring *)value; - (int)age; - (void)setage:(int)age; - (BOOL)canLegallyVote; - (void)castballot; @end 30

Object Ownership #import "Person.h" @implementation Person @end 31

Object Ownership #import "Person.h" @implementation Person - (NSString *)name { return name; - (void)setname:(nsstring *)newname { @end 31

Object Ownership #import "Person.h" @implementation Person - (NSString *)name { return name; - (void)setname:(nsstring *)newname { @end if (name!= newname) { [name release]; name = [newname retain]; // name s retain count has been bumped up by 1 31

Object Ownership #import "Person.h" @implementation Person - (NSString *)name { return name; - (void)setname:(nsstring *)newname { @end 31

Object Ownership #import "Person.h" @implementation Person - (NSString *)name { return name; - (void)setname:(nsstring *)newname { @end if (name!= newname) { [name release]; name = [newname copy]; // name has retain count of 1, we own it 31

Releasing Instance Variables #import "Person.h" @implementation Person - (void)dealloc { // Do any cleanup that s necessary [name release]; // when we re done, call super to clean us up [super dealloc]; @end 32

Autorelease 33

Returning a newly created object - (NSString *)fullname { NSString *result; result = [[NSString alloc] initwithformat:@ %@ %@, firstname, lastname]; return result; Wrong: result is leaked! 34

Returning a newly created object - (NSString *)fullname { NSString *result; result = [[NSString alloc] initwithformat:@ %@ %@, firstname, lastname]; [result release]; return result; Wrong: result is released too early! Method returns bogus value 34

Returning a newly created object - (NSString *)fullname { NSString *result; result = [[NSString alloc] initwithformat:@ %@ %@, firstname, lastname]; [result autorelease]; return result; Just right: result is released, but not right away Caller gets valid object and could retain if needed 34

Autoreleasing Objects Calling -autorelease flags an object to be sent release at some point in the future Let s you fulfill your retain/release obligations while allowing an object some additional time to live Makes it much more convenient to manage memory Very useful in methods which return a newly created object 35

Method Names & Autorelease Methods whose names includes alloc, copy, or new return a retained object that the caller needs to release NSMutableString *string = [[NSMutableString alloc] init]; // We are responsible for calling -release or -autorelease [string autorelease]; All other methods return autoreleased objects NSMutableString *string = [NSMutableString string]; // The method name doesn t indicate that we need to release it // So don t- we re cool! This is a convention- follow it in methods you define! 36

How does -autorelease work? Object is added to current autorelease pool Autorelease pools track objects scheduled to be released When the pool itself is released, it sends -release to all its objects UIKit automatically wraps a pool around every event dispatch 37

Autorelease Pools (in pictures) Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool [object autorelease]; Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool released Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) [object release]; Pool [object release]; Objects autoreleased here go into pool [object release]; Pool released Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Autorelease Pools (in pictures) Pool Objects autoreleased here go into pool Pool released Pool created Launch app App initialized Load main nib Wait for event Handle event Exit app 38

Hanging Onto an Autoreleased Object Many methods return autoreleased objects Remember the naming conventions... They re hanging out in the pool and will get released later If you need to hold onto those objects you need to retain them Bumps up the retain count before the release happens name = [NSMutableString string]; // We want to name to remain valid! [name retain]; //... // Eventually, we ll release it (maybe in our -dealloc?) [name release]; 39

Side Note: Garbage Collection Autorelease is not garbage collection Objective-C on iphone OS does not have garbage collection 40

Objective-C Properties 41

Properties Provide access to object attributes Shortcut to implementing getter/setter methods Also allow you to specify: read-only versus read-write access memory management policy 42

Defining Properties #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 43

Defining Properties #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 43

Defining Properties #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 43

Defining Properties #import <Foundation/Foundation.h> @interface Person : NSObject { // instance variables NSString *name; int age; // property declarations @property int age ; @property (copy) NSString * name; @property (readonly) BOOL canlegallyvote ; - (void)castballot; @end 43

Defining Properties #import <Foundation/Foundation.h> @interface Person : NSObject { // instance variables NSString *name; int age; // property declarations @property int age; @property (copy) NSString *name; @property (readonly) BOOL canlegallyvote; - (void)castballot; @end 44

Synthesizing Properties @implementation Person - (int)age { return age; - (void)setage:(int)value { age = value; - (NSString *)name { return name; - (void)setname:(nsstring *)value { if (value!= name) { [name release]; name = [value copy]; - (void)canlegallyvote {... 45

Synthesizing Properties @implementation Person - (int)age { return age; - (void)setage:(int)value { age = value; - (NSString *)name { return name; - (void)setname:(nsstring *)value { if (value!= name) { [name release]; name = [value copy]; - (void)canlegallyvote {... 45

Synthesizing Properties @implementation Person - (int)age { return age; - (void)setage:(int)value { age = value; - (NSString *)name { return name; - (void)setname:(nsstring *)value { if (value!= name) { [name release]; name = [value copy]; - (void)canlegallyvote {... 45

Synthesizing Properties @implementation Person @synthesize age; @synthesize name; - (BOOL)canLegallyVote { return (age > 17); @end 46

Property Attributes Read-only versus read-write! @property int age; // read-write by default @property (readonly) BOOL canlegallyvote; Memory management policies (only for object properties) @property (assign) NSString *name; // pointer assignment @property (retain) NSString *name; // retain called @property (copy) NSString *name; // copy called 47

Property Names vs. Instance Variables Property name can be different than instance variable @interface Person : NSObject { int numberofyearsold; @property int age; @end @implementation Person @synthesize age = numberofyearsold; @end 48

Properties Mix and match synthesized and implemented properties @implementation Person @synthesize age; @synthesize name; - (void)setage:(int)value { age = value; // now do something with the new age value... @end Setter method explicitly implemented Getter method still synthesized 49

Properties In Practice Newer APIs use @property Older APIs use getter/setter methods Properties used heavily throughout UIKit APIs Not so much with Foundation APIs You can use either approach Properties mean writing less code, but magic can sometimes be non-obvious 50

Dot Syntax and self When used in custom methods, be careful with dot syntax for properties defined in your class References to properties and ivars behave very differently @interface Person : NSObject { NSString *name; @property (copy) NSString *name; @end @implementation Person - (void)dosomething { name = @ Fred ; self.name = @ Fred ; // accesses ivar directly! // calls accessor method 51

Common Pitfall with Dot Syntax What will happen when this code executes? @implementation Person - (void)setage:(int)newage { self.age = newage; @end This is equivalent to: @implementation Person - (void)setage:(int)newage { [self setage:newage]; // Infinite loop! @end 52

Further Reading Objective-C 2.0 Programming Language Defining a Class Declared Properties Memory Management Programming Guide for Cocoa 53

Questions? 54