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

Similar documents
Introduction to Objective-C. Kevin Cathey

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

iphone Objective-C Exercises

Praktikum Entwicklung von Mediensystemen mit

iphone SDK Enrolled students will be invited to developer program Login to Program Portal Request a Certificate Download and install the SDK

ios Development Tutorial Nikhil Yadav CSE 40816/60816: Pervasive Health 09/09/2011

Objective-C and Cocoa User Guide and Reference Manual. Version 5.0

INTRODUCTION TO IOS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 13 02/22/2011

MA-WA1920: Enterprise iphone and ipad Programming

Creating a Custom Class in Xcode

Objective C and iphone App

Objective-C for Experienced Programmers

Assignment I Walkthrough

Introduction to iphone Development

ios Dev Crib Sheet In the Shadow of C

ios App Development for Everyone

NSPersistentDocument Core Data Tutorial for Mac OS X v10.4. (Retired Document)

Your First ios Application

ios Dev Fest Research Network Operations Center Thursday, February 7, 13

This documentation is made available before final release and is subject to change without notice and comes with no warranty express or implied.

Praktikum Entwicklung von Mediensystemen mit ios

Lecture 1 Introduction to Android

Application Programming on the Mac COSC346

Key-Value Coding Programming Guide

AC : OBJECTIVE-C VERSUS JAVA FOR SMART PHONE AP- PLICATIONS

Common Lisp ObjectiveC Interface

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Objective-C Internals

Chapter 1. Introduction to ios Development. Objectives: Touch on the history of ios and the devices that support this operating system.

Developing Applications for ios

Please note that this SDK will only work with Xcode or above. If you need an SDK for an older Xcode version please support.

Assignment 1: Matchismo

Introduction to Eclipse

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Send from your App Part 1

ECS 165B: Database System Implementa6on Lecture 2

An Introduction to Modern Software Development Tools Creating A Simple GUI-Based Tool Appleʼs XCode Version 3.2.6

Using the Caché Objective-C Binding

From C++ to Objective-C

Learning ios Programming

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Microsoft Tag Scanning SDK for iphone & Android Apps

The C Programming Language course syllabus associate level

Cucumber: Finishing the Example. CSCI 5828: Foundations of Software Engineering Lecture 23 04/09/2012

WHAT ELSE CAN YOUR HOME PHONE DO?

Moving from CS 61A Scheme to CS 61B Java

ITP 342 Mobile App Development. Notifications

17. November Übung 1 mit Swift. Architektur verteilter Anwendungen. Thorsten Kober Head Solutions ios/os X, SemVox GmbH

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Contents. About Testing with Xcode 4. Quick Start 7. Testing Basics 23. Writing Test Classes and Methods 28. At a Glance 5 Prerequisites 6 See Also 6

Java EE Web Development Course Program

Sensi TM. Wi-Fi Programmable Thermostat SCHEDULING GUIDE. Version: March Emerson Electric Co. All rights reserved.

Leak Check Version 2.1 for Linux TM

Programming Cocoa with Ruby Create Compelling Mac Apps Using RubyCocoa

ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012

Salesforce Classic Guide for iphone

ios App Development for Everyone

Developing Applications for ios

RingCentral from AT&T Desktop App for Windows & Mac. User Guide

Programming Embedded Systems

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Lecture 5: Java Fundamentals III

RingCentral for Desktop. UK User Guide

ios Application Security

Chapter 5 Names, Bindings, Type Checking, and Scopes

Android Application Development Course Program

How To Develop An App For Ios (Windows)

Operating Systems and Networks

Java Interview Questions and Answers

Efficient Cross-Platform Method Dispatching for Interpreted Languages

ios Application Development &

eggon SDK for ios 7 Integration Instructions

Habanero Extreme Scale Software Research Project

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

Xcode Project Management Guide. (Legacy)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Stack Allocation. Run-Time Data Structures. Static Structures

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Crash Course in Java

Accessibility on ios. Make an app for everyone. Chris Fleizach ios Accessibility. Wednesday, December 1, 2010

GO!Enterprise MDM Device Application User Guide Installation and Configuration for ios with TouchDown

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

geniusport mobility training experts

Using PyObjC for Developing Cocoa Applications with Python

Provide instructions for installing the VMware View Client a non-wellmont device. These instructions are for a Windows based OS.

Introduction to the BackgroundWorker Component in WPF

Sources: On the Web: Slides will be available on:

PHONE USER 1 GUIDE. Morristown (MUS) Local Customer Calling FROM: Morristown (Area Code 423): 307, 317, 318, 522, 581, 585, 586, 587

Programming Project 1: Lexical Analyzer (Scanner)

Setting Up Your Android Development Environment. For Mac OS X (10.6.8) v1.0. By GoNorthWest. 3 April 2012

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Tag Specification Document

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer

Lecture 22: C Programming 4 Embedded Systems

ios Team Administration Guide (Legacy)

Computer Programming I & II*

Transcription:

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

Announcements Assignments 1A and 1B due Thursday 4/9 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

Announcements Assignments 2A and 2B due Tuesday 4/14 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 Monday 4/13! Assignment contains extensive walkthrough

Announcements Troy s office hours: Mondays 12-2, Gates B26A Paul s office hours: Tuesdays 12-2, Gates 463 This week s optional Friday session (4/10)! 200-205, 3:15-4:05 PM! Debugging crash course, not to be missed! Class newsgroup (Stanford-only) at su.class.cs193p! No gopher site yet...

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

Custom Classes

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

Review: Methods, Selectors, Messages Method! Behavior associated with an object - (NSString *)name { // Implementation - (void)setname:(nsstring *)name { // Implementation

Review: Methods, Selectors, Messages Selector! Name for referring to a method! Includes colons to indicate arguments! Doesn t actually include arguments or indicate types SEL myselector = @selector(name); SEL anotherselector = @selector(setname:); SEL lastselector = @selector(dostuff:withthing:andthing:);

Review: Methods, Selectors, Messages Message! The act of performing a selector on an object! With arguments, if necessary NSString *name = [myperson name]; [myperson setname:@ New Name ];

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

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

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

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

Implementing custom class Implement setter/getter methods Implement action methods

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

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

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; //...

Object Lifecycle

Object Lifecycle Creating objects Memory management Destroying objects

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

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

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

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];

Finishing Up With an Object Person *person = nil; person = [[Person alloc] init]; [person setname:@ Alan Cannistraro ]; [person setage:29]; [person setwishfulthinking:yes]; [person castballot]; // What do we do with person when we re done?

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...

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

Balanced Calls Person *person = nil; person = [[Person alloc] init]; [person setname:@ Alan Cannistraro ]; [person setage:29]; [person setwishfulthinking:yes]; [person castballot]; // When we re done with person, release it [person release]; // person will be destroyed here

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

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

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

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

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

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

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

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

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

Autorelease

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

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

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

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

Method Names & Autorelease Methods whose names includes alloc or copy 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!

How does -autorelease work? Magic! (Just kidding...)

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

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

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

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

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

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

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

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

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

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];

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

Objective-C Properties

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

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

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

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

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

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

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) { [value release]; name = [value copy]; - (void)canlegallyvote {...

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) { [value release]; name = [value copy]; - (void)canlegallyvote {...

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) { [value release]; name = [value copy]; - (void)canlegallyvote {...

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

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

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

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

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

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 ; // accesses ivar directly!!! self.name = @ Fred ; // calls accessor method

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

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

Questions?