Design Phase. Create a class Person. Determine the superclass. NSObject (in this case)

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

Announcement. Final Project Proposal Presentations and Updates

Mobile Application Development

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

Advanced Object- C Features

Objective-C Part 2 (ECS189H) Ken Joy Serban Porumbescu

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

ITP 342 Advanced Mobile App Dev. Memory

COMP327 Mobile Computing Session: Tutorial Objective-C and the Foundation Framework

Announcements. Today s Topics

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

Mobile Application Development

Objective-C and COCOA Applications

CS193p Spring 2010 Thursday, April 29, 2010

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

ITP 342 Mobile App Dev. Fundamentals

Objective-C ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Mobile Application Programming. Objective-C Classes

Object Oriented Programming in C++

Introductory ios Development

Mobile Application Programming. Memory Management

Object-Oriented Programming with Objective-C. Lecture 2

Review (Basic Objective-C)

src7-malan/c/array/array/main.c // main.c // Array // David J. Malan // Harvard University // // Demonstrates arrays. 11.

Collections & Memory Management. Lecture 2

CS 47. Beginning iphone Application Development

COMP327 Mobile Computing Session: Lecture Set 1a - Swift Introduction and the Foundation Framework Part 2

Mobile Application Development

ios Development Lecture 1 Introduction to Objective-C Ing. Simone Cirani

ios: Objective-C Primer

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

IPHONE. Development Jump Start. phil nash levelofindirection.com

CS193P: HelloPoly Walkthrough

Praktikum Entwicklung von Mediensystemen mit ios

Contents at a Glance

Objective-C. Stanford CS193p Fall 2013

CS193P - Lecture 10. iphone Application Development. Performance

ITP 342 Mobile App Dev. Fundamentals

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011

Objective-C and Cocoa User Guide and Reference Manual

Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer

My First iphone App. 1. Tutorial Overview

Memory Management: The Details

Assignment II: Foundation Calculator

iphone Application Tutorial

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import "Deck.

A little more Core Data

Cocoa. Last Week... Music 3SI: Introduction to Audio/Multimedia App. Programming. Today... Why Cocoa? Wikipedia - Cocoa

Principles of Programming Languages. Objective-C. Joris Kluivers

Intro to Native ios Development. Dave Koziol Arbormoon Software, Inc.

CMSC 330: Organization of Programming Languages

About MSDOSX. Lecture 0

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

Mac OS X and ios operating systems. Lecture 2 Objective-C. Tomasz Idzi

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5

Topics in Mobile Computing

iphone Programming Patrick H. Madden SUNY Binghamton Computer Science Department

Your First iphone Application

Static, Final & Memory Management

CS 11 C track: lecture 5

Memory management COSC346

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

COCOA WORKSHOP PART 1. Andreas Monitzer

Motivation was to facilitate development of systems software, especially OS development.

CS 241 Honors Memory

Bindings Example Exercise James Dempsey - WWDC Pre-Show Cocoa Workshop

Your First iphone OS Application

src2/section2.0/section2/main.m // main.m // Students7 // David J. Malan // Harvard University // // Demonstrates mutable arrays.

Thread Sanitizer and Static Analysis

CS193P - Lecture 2. iphone Application Development. Objective-C Foundation Framework

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

Coding Standards for GNUstep Libraries

Porting Objective-C to Swift. Richard Ekle

the gamedesigninitiative at cornell university Lecture 9 Memory Management

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C?

1.The basics 5 Comments 5 Variables and basic types 6 Operators 8 Object variables 10 A note on prefixes and namespaces 11

CMSC 330: Organization of Programming Languages

EMBEDDED SYSTEMS PROGRAMMING OO Basics

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Structure of Programming Languages Lecture 10

In Java we have the keyword null, which is the value of an uninitialized reference type

a data type is Types

CA31-1K DIS. Pointers. TA: You Lu

Motivation was to facilitate development of systems software, especially OS development.

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Developing Applications for ios

Working Effectively with Objective-C on iphone OS. Blaine Garst Wizard of Runtimes

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding

Lecture 13: more class, C++ memory management

When we re first learning Cocoa (or Java, or Qt, or any other application framework),

The MVC Design Pattern

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Page 1. GUI Programming. Lecture 13: iphone Basics. iphone. iphone

Run-time Environments

Run-time Environments

Compiler Construction

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Transcription:

Design Phase Create a class Person Determine the superclass NSObject (in this case) 8

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

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 Tuesday, January 12, 2010 9

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

Class interface declared in header file Tuesday, January 12, 2010 10

Class interface declared in header file @interface Person @end 10

Class interface declared in header file @interface Person : NSObject @end 10

Class interface declared in header file #import <Foundation/Foundation.h> @interface Person : NSObject @end 10

Class interface declared in header file #import <Foundation/Foundation.h> @interface Person { : NSObject @end 10

Class interface declared in header file #import <Foundation/Foundation.h> @interface Person : NSObject { // instance variables NSString *name; int age; @end 10

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 13

Class Implementation #import "Person.h" 13

Class Implementation #import "Person.h" @implementation Person @end 13

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 14

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 15

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 18

Object Creation Two step process allocate memory to store the object initialize object state 18

Object Creation Two step process allocate memory to store the object initialize object state + alloc Class method that knows how much memory is needed 18

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 Tuesday, January 12, 2010 19

Create = Allocate + Initialize Person *person = nil; Tuesday, January 12, 2010 19

Create = Allocate + Initialize Person *person = nil; person = [[Person alloc] init]; Tuesday, January 12, 2010 19

Implementing your own -init method #import "Person.h" @implementation Person @end 20

Implementing your own -init method #import "Person.h" @implementation Person - (id)init { @end 20

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

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

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

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 Allocation Destruction 23

Memory Management Allocation Destruction C malloc free 23

Memory Management C Objective-C Allocation malloc alloc Destruction free dealloc 23

Memory Management C Objective-C Allocation malloc alloc Destruction free dealloc Calls must be balanced Otherwise your program may leak or crash 23

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 24

Reference Counting Every object has a retain count Defined on NSObject As long as retain count is > 0, object is alive and valid 24

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 24

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 24

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 24

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

Balanced Calls Person *person = nil; person = [[Person alloc] init]; [person setname:@ Jimmy Jones ]; [person setage:32]; [person castballot]; [person dosomethingelse]; 25

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 26

Reference counting in action Person *person = [[Person alloc] init]; 26

Reference counting in action Person *person = [[Person alloc] init]; Retain count begins at 1 with +alloc 26

Reference counting in action Person *person = [[Person alloc] init]; Retain count begins at 1 with +alloc [person retain]; 26

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 26

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

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 26

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

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 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 dosomething]; // Crash! 27

Messaging deallocated objects Person *person = [[Person alloc] init]; //... [person release]; // Object is deallocated Tuesday, January 12, 2010 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 @end 28

Implementing a -dealloc method #import "Person.h" @implementation Person - (void)dealloc { @end 28

Implementing a -dealloc method #import "Person.h" @implementation Person - (void)dealloc { // Do any cleanup that s necessary //... @end 28

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 @end 32

Releasing Instance Variables #import "Person.h" @implementation Person - (void)dealloc { @end 32

Releasing Instance Variables #import "Person.h" @implementation Person - (void)dealloc { // Do any cleanup that s necessary [name release]; @end 32

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

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; 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]; return result; 34

Returning a newly created object - (NSString *)fullname { NSString *result; result = [[NSString alloc] initwithformat:@ %@ %@, firstname, lastname]; [result autorelease]; return result; 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 36

Method Names & Autorelease Methods whose names includes alloc, copy, or new return a retained object that the caller needs to release 36

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

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 36

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! 36

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? 37

How does -autorelease work? Object is added to current autorelease pool 37

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 37

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 39

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 48

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 51

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 52

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