Presentation is loading. Please wait.

Presentation is loading. Please wait.

EEC-492/693/793 iPhone Application Development

Similar presentations


Presentation on theme: "EEC-492/693/793 iPhone Application Development"— Presentation transcript:

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

2 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

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

4 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

5 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 // do other initialization... } return self; @end 12/1/2018 EEC492/693/793 - iPhone Application Development

6 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 Name”]; } - (id)initWithName:(NSString *)name { return [self initWithName:name age:0]; 12/1/2018 EEC492/693/793 - iPhone Application Development

7 Finishing Up With an Object
Person *person = nil; person = [[Person alloc] init]; [person 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

8 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

9 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

10 EEC492/693/793 - iPhone Application Development
Balanced Calls Person *person = nil; person = [[Person alloc] init]; [person 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

11 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

12 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

13 Implementing a -dealloc method
#import 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

14 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

15 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

16 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

17 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

18 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] firstName, lastName]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

19 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] firstName, lastName]; [result release]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

20 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] firstName, lastName]; [result autorelease]; return result; } 12/1/2018 EEC492/693/793 - iPhone Application Development

21 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

22 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

23 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

24 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

25 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

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

27 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

28 Showing the Action Sheet
In Control_FunViewController.m, the button’s action method: - (IBAction)buttonPressed { UIActionSheet *actionSheet = [[UIActionSheet alloc] you sure?" delegate:self // our view controller itself is the delegate Way!" 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

29 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

30 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 can breathe easy, everything went OK."; UIAlertView *alert = [[UIAlertView alloc] was done" message:msg delegate:self 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

31 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: 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

32 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 UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0]; [doSomethingButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; UIImage *buttonImagePressed = [UIImage UIImage *stretchableButtonImagePressed = [buttonImagePressed [doSomethingButton setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted]; } 12/1/2018 EEC492/693/793 - iPhone Application Development

33 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

34 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


Download ppt "EEC-492/693/793 iPhone Application Development"

Similar presentations


Ads by Google