EEC-492/693/793 iPhone Application Development

Slides:



Advertisements
Similar presentations
Objective-C Lecture 2 Memory management Memory management in OC is semi- automatic: The programmer must allocate memory for objects either a) explicitly.
Advertisements

Table Views UITableView. Overview Table view basics Tables display lists of data Each item in a tables list is a row Tables can have an unlimited number.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 6 Object Oriented Programming in Java Language Basics Objects.
Written by: Dr. JJ Shepherd
Create a calculator– 2nd iPhone programming exercise CSE 391 Fall 2012.
IOS and AddressBook CS4521. Address Book UI Framework Exploring Contacts.
Introduction to Objective-C and Xcode (Part 1) FA 175 Intro to Mobile App Development.
UIAlertView, UIActionSheet, and Facebook Connection Lecture 4 1.
View Controllers (second part) Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
IPhone Development Crash Course By Dylan Harris
IPhone 101. Outline Objective-C Random bits of the API Using the simulator Debugging with Xcode.
Storyboards Managing multiple views. Overview Create a single view application Give the project a name and click “Use Storyboards” and “Use Automatic.
Sprite Animation CSE 391 Fall 2012 Tony Scarlatos.
Xcode testing Using XCTest.
iOS components in Swift
Objective C Basics. It’s C with Some Extras!  Cross Platform language  Mac  Linux/UNIX  Windows  Layer above C (Superset)  Adds Object-Oriented.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Tabbed Views UITabBarController. Controller Architecture UITabBarController Controls the first view that the user sees The view controller class (and.
IOS with Swift Hello world app.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
View Controllers Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
C++ Memory Overview 4 major memory segments Key differences from Java
Gestures UIGestureRecognizer.
Objective-C Memory management Memory management is semi-automatic: The programmer must allocate memory for objects either a) explicitly (alloc) or b) indirectly.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Nav Controllers UINavigationController. Overview Nav Controller basics Like a tabview controller, a navViewController manages views A navigationViewController.
Processes CS 6560: Operating Systems Design. 2 Von Neuman Model Both text (program) and data reside in memory Execution cycle Fetch instruction Decode.
WinCvs. WinCVS WinCvs is a window based version control system. Use WinCvs when  You want to save every version of your file you have ever created. CVS.
The Controller in MVC of iOS CS4521. The controller in the MVC  Controller  Knows about model and view objects  The brains of the operation  Manages.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 UI Alert View iPhone/iPad, iOS Development Tutorial.
1 Reverse a String iPhone/iPad, iOS Development Tutorial.
Creating a GUI Class An example of class design using inheritance and interfaces.
Written by: Dr. JJ Shepherd
2/20/2016 EEC492/693/793 - iPhone Application Development 12/20/2016 EEC492/693/793 - iPhone Application Development 1 EEC-492/693/793 iPhone Application.
Introduction to Objective-C and Xcode (Part 4) FA 175 Intro to Mobile App Development.
Generics, Exceptions and Undo Command
iOS - First Application Anatomy
Lesson One – Creating a thread
Learning the Basics – Lesson 1
Pointers, Polymorphism, and Memory Allocation
Storage Management.
Process Creation Processes get created (and destroyed) all the time in a typical computer Some by explicit user command Some by invocation from other running.
Chapter 5 Conclusion CIS 61.
System Structure and Process Model
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
Affordable iPhone Mobile Apps Development Services Company
Advanced Programming Behnam Hatami Fall 2017.
System Structure and Process Model
EEC-492/693/793 iPhone Application Development
Lecture 11 C Parameters Richard Gesick.
EEC-492/693/793 iPhone Application Development
System Structure B. Ramamurthy.
System Structure and Process Model
Operating Systems Lecture 6.
Process & its States Lecture 5.
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
Object-Oriented Programming: Inheritance and Polymorphism
Objects Managing a Resource
Game Over Module 4 Lesson 2.
EEC-492/693/793 iPhone Application Development
Getting started – Example 1
EEC-492/693/793 iPhone Application Development
CMPE212 – Reminders Assignment 2 due next Friday.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

EEC-492/693/793 iPhone Application Development Lecture 6 Wenbing Zhao & Nigamanth Sridhar 12/1/2018 EEC492/693/793 - iPhone Application Development

Outline More in-depth Objective-C Control Fun App (part III) Objective lifecycle autorelease Control Fun App (part III) Objective-C part is shamelessly taken from Stanford CS193P winter 2010 lecture 3 12/1/2018 12/1/2018 EEC492/693/793 - iPhone Application Development EEC492/693/793 - iPhone Application Development 2

EEC492/693/793 - iPhone Application Development Object Lifecycle Creating objects Memory management Destroying objects 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development 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]; 12/1/2018 EEC492/693/793 - iPhone Application Development

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 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development 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]; 12/1/2018 EEC492/693/793 - iPhone Application Development

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? 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development Memory Management Allocation Destruction C Malloc Free Objective-C Alloc dealloc Calls must be balanced, otherwise, your program may leak or crash 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development 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 of 1 -retain increments retain count -release decrements retain count When retain count reaches 0, object is destroyed -dealloc method invoked automatically 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development 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 12/1/2018 EEC492/693/793 - iPhone Application Development

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 Retain count decreases to 0, -dealloc automatically called 12/1/2018 EEC492/693/793 - iPhone Application Development

Messaging deallocated objects Person *person = [[Person alloc] init]; // ... [person release]; // Object is deallocated person = nil; [person doSomething]; // No effect Tuesday, 12/1/2018 EEC492/693/793 - iPhone Application Development

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 12/1/2018 EEC492/693/793 - iPhone Application Development

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 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development 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 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development Object Ownership #import "Person.h“ @implementation Person - (NSString *)name { return name; } (void)setName:(NSString *)newName { if (name != newName) { [name release]; // if we don’t do this, we would lose the reference // to the object pointed to by name after the assignment, which would // cause a memory leak name = [newName retain]; // Person is taking ownership of newName // name’s retain count has been bumped up by 1 @end There are many alternatives to the implementation provided above 12/1/2018 EEC492/693/793 - iPhone Application Development

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 12/1/2018 EEC492/693/793 - iPhone Application Development

Returning a Newly Created Object Attempt #1 Not ideal: caller must remember to call release on the NSString after using it - (NSString *)fullName { NSString *result; result = [[NSString alloc] initWithFormat:@“%@ %@”, firstName, lastName]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

Returning a Newly Created Object Attempt #2 Wrong: result is release too early! Method would return bogus value - (NSString *)fullName { NSString *result; result = [[NSString alloc] initWithFormat:@“%@ %@”, firstName, lastName]; [result release]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

Returning a Newly Created Object Attempt #3 Just right: result is released, but not right away Caller gets valid object and could retain if needed - (NSString *)fullName { NSString *result; result = [[NSString alloc] initWithFormat:@“%@ %@”, firstName, lastName]; [result autorelease]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

Autoreleasing Objects Calling -autorelease flags an object to be sent release at some point in the future Let 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 12/1/2018 EEC492/693/793 - iPhone Application Development

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! 12/1/2018 EEC492/693/793 - iPhone Application Development

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 is not garbage collection Objective-C on iPhone OS does not have garbage collection 12/1/2018 EEC492/693/793 - iPhone Application Development

Autorelease Pools (in pictures) [object release]; Pool Pool Pool created Pool Pool Pool Objectives autoreleased Here go into pool [object release]; Pool created Pool created Pool created Pool created Pool created Pool created Pool created Pool created Pool created [object autorelease]; [object release]; Pool released Pool created Pool created Pool created Pool created Launch app App initialized Load main nib Handle event Exit app Wait for event 12/1/2018 EEC492/693/793 - iPhone Application Development

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 the name to remain valid! [name retain]; // ... // Eventually, we’ll release it (maybe in our -dealloc?) [name release]; 12/1/2018 EEC492/693/793 - iPhone Application Development

Control Fun App (Part III) 12/1/2018 EEC492/693/793 - iPhone Application Development

Implementing the Action Sheet and Alert Action sheets are used to force the user to make a choice between two or more items The user is unable to continue using the app until they have tapped one of the buttons Action sheets are often used to confirm a potentially dangerous or irreversible action A view that forces the user to make a choice before they are allowed to continue using their app is known as a modal view Alerts also force users to respond before they are allowed to continue using their app Alerts are used more to inform the user that something important or unusual has occurred Often present a single button: an alert is not used to solicit a choice 12/1/2018 EEC492/693/793 - iPhone Application Development

Showing the Action Sheet In Control_FunViewController.m, the button’s action method: - (IBAction)buttonPressed { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?" delegate:self // our view controller itself is the delegate cancelButtonTitle:@"No Way!" destructiveButtonTitle:@"Yes, I'm Sure!" otherButtonTitles:nil]; // only two buttons shown [actionSheet showInView:self.view]; // the view is the parent of actionSheet [actionSheet release]; } Why self.view: because view is private instance variable, and it must be accessed via the accessor 12/1/2018 EEC492/693/793 - iPhone Application Development

Conforming to the Action Sheet Delegate Method Action sheets and alerts both use delegates so that they know what object to notify when the user has responded In the Control Fun app, we want the UIViewController object to be notified when the action sheet is dismissed Our controller, therefore, would act as the delegate It must conform to a protocol called UIActionSheetDelegate Should declare action method in header file: - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex @interface Control_FunViewController : UIViewController <UIActionSheetDelegate> { UITextField *nameField; UITextField *numberField; UILabel *sliderLabel; ... 12/1/2018 EEC492/693/793 - iPhone Application Development

Implementing the Protocol method - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { if (buttonIndex != [actionSheet cancelButtonIndex]) { NSString *msg = nil; if (nameField.text.length > 0) msg = [[NSString alloc] initWithFormat: @"You can breathe easy, %@, everything went OK.", nameField.text]; else msg = @"You can breathe easy, everything went OK."; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Something was done" message:msg delegate:self cancelButtonTitle:@"Phew!" otherButtonTitles:nil]; [alert show]; [alert release]; [msg release]; } Alerts, unlike action sheets, are not tied to a particular view, so we just tell the alert to show itself without specifying a parent view. Add this method to Control_FunViewController.m 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development Spiffing up the Button Most buttons you see on your iPhone are drawn using images You can specify a kind of template image that the iPhone will use when drawing your buttons Offered in the Apple UICatalog sample code: http://developer.apple.com/iphone/library/samplecode/UICatalog/index.html Go to UICatalog app’s Images subfolder, and add blueButton.png and whiteButton.png to the Control Fun project Go to Interface Builder, single-click the Do Something button, and open the attributes inspector Use 1st pop-up menu to change the type to Custom More work to be done in Xcode 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development Spiffing up the Button Build a custom button using the viewDidLoad method The code sets the background image for the button, and while being touched, it change from white image to blue image Go to Xcode, add viewDidLoad: method to Control_FunViewController.m - (void)viewDidLoad { UIImage *buttonImageNormal = [UIImage imageNamed:@"whiteButton.png"]; UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0]; [doSomethingButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; UIImage *buttonImagePressed = [UIImage imageNamed:@"blueButton.png"]; UIImage *stretchableButtonImagePressed = [buttonImagePressed [doSomethingButton setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted]; } 12/1/2018 EEC492/693/793 - iPhone Application Development

Control States and Stretchable Images Every UI control has four control states: Normal: default state Highlighted: when it is currently being used For a button, this would be while the user has a finger on the button Disabled: it has been turned off (by unchecking the Enabled checkbox in the inspector Selected: this control is turned on or selected It can continue to be selected when the user is no longer directly using the control Not all controls support this state Stretchable images Resizable image that knows how to resize itself intelligently (maintains correct appearance) End caps should not be resized If we had specified the button image right in Interface Builder, it would resize the entire image evenly, and our button would look weird at most sizes. 12/1/2018 EEC492/693/793 - iPhone Application Development

EEC492/693/793 - iPhone Application Development Finishing Up Add viewDidUnload: method to Control_FunViewController.m to free up outlets when the view is unloaded Save, build and run! - (void)viewDidUnload { self.nameField = nil; // release the old object and retain nil self.numberField = nil; self.sliderLabel = nil; self.leftSwitch = nil; self.rightSwitch = nil; self.doSomethingButton = nil; [super viewDidUnload]; } 12/1/2018 EEC492/693/793 - iPhone Application Development