ITP 342 Advanced Mobile App Dev. Memory

Similar documents
ITP 342 Mobile App Dev. Fundamentals

Announcement. Final Project Proposal Presentations and Updates

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

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

Mobile Application Development

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

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

Mobile Application Programming. Objective-C Classes

Mobile Application Programming. Memory Management

ITP 342 Advanced Mobile App Dev. Memory

Objective-C and COCOA Applications

ios: Objective-C Primer

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

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

ITP 342 Mobile App Dev. Connections

My First iphone App. 1. Tutorial Overview

Objective-C. Stanford CS193p Fall 2013

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

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

Contents at a Glance

CS193P: HelloPoly Walkthrough

CS193p Spring 2010 Thursday, April 29, 2010

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

iphone Programming Patrick H. Madden SUNY Binghamton Computer Science Department

ITP 342 Mobile App Dev. Connections

Your First iphone Application

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

Principles of Programming Languages. Objective-C. Joris Kluivers

Memory Management: The Details

iphone Application Tutorial

Your First iphone OS Application

Assignment II: Foundation Calculator

Structure of Programming Languages Lecture 10

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

igc Garbage Collection

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

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

Ch. 11: References & the Copy-Constructor. - continued -

Introductory ios Development

My First iphone App (for Xcode version 6.4)

Praktikum Entwicklung von Mediensystemen mit ios

The MVC Design Pattern

the gamedesigninitiative at cornell university Lecture 9 Memory Management

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

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

Mobile Application Development

Memory management COSC346

SDK Programming for Web Developers

ITP 342 Mobile App Dev. Fundamentals

CS 47. Beginning iphone Application Development

CMSC 330: Organization of Programming Languages

Review (Basic Objective-C)

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

Garbage Collection. CS 351: Systems Programming Michael Saelee

iphone Application Programming Lecture 3: Swift Part 2

CMSC 330: Organization of Programming Languages

Item 18: Implement the Standard Dispose Pattern

ios Core Data Example Application

Thread Sanitizer and Static Analysis

Vector and Free Store (Pointers and Memory Allocation)

ITP 342 Advanced Mobile App Dev. Core Data

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

Advanced Object- C Features

Porting Objective-C to Swift. Richard Ekle

Data Structures (list, dictionary, tuples, sets, strings)

Heap Management. Heap Allocation

Compiler Construction D7011E

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

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.

Topics in Mobile Computing

ITP 342 Mobile App Dev. Unit Testing

epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE

Lecture 13: more class, C++ memory management

1 Dynamic Memory continued: Memory Leaks

Designing iphone Applications

Objective-C and Cocoa User Guide and Reference Manual

Robust Memory Management Schemes

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

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

A little more Core Data

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

Mobile Application Development


Chapter 17 vector and Free Store. Bjarne Stroustrup

CS61C : Machine Structures

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

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

CS 103 Lab The Files are *In* the Computer

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

CS 241 Honors Memory

Computer Science, a Mac, and You. Kevin Cathey Junior, Computer Science

ITP 342 Mobile App Development. Data Persistence

Assignment I Walkthrough

Praktikum Entwicklung von Mediensystemen mit

ITP 342 Mobile App Development. Data Persistence

My First Cocoa Program

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

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

ITP 342 Mobile App Dev. Interface Builder in Xcode

Transcription:

ITP 342 Advanced Mobile App Dev Memory

Memory Management Objective-C provides two methods of application memory management. 1. In the method described in this guide, referred to as manual retain-release or MRR, you explicitly manage memory by keeping track of objects you own. This is implemented using a model, known as reference counting, that the Foundation class NSObject provides in conjunction with the runtime environment. 2. In Automatic Reference Counting, or ARC, the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for you at compile-time. You are strongly encouraged to use ARC for new projects. If you use ARC, there is typically no need to understand the underlying implementation, although it may in some situations be helpful. 2

Memory Management Policy Application memory management is the process of allocating memory during your program s runtime, using it, and freeing it when you are done with it. A well-written program uses as little memory as possible. In Objective-C, it can also be seen as a way of distributing ownership of limited memory resources among many pieces of data and code. Although memory management is typically considered at the level of an individual object, your goal is actually to manage object graphs. You want to make sure that you have no more objects in memory than you actually need. 3

4

Memory Management Policy The basic model used for memory management in a reference-counted environment is provided by a combination of methods defined in the NSObject protocol and a standard method naming convention. The NSObject class also defines a method, dealloc, that is invoked automatically when an object is deallocated. 5

Basic Memory Management Rules The memory management model is based on object ownership. Any object may have one or more owners. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically. 6

Cocoa's Policies You own any object you create You create an object using a method whose name begins with alloc, new, copy, or mutablecopy You can take ownership of an object using retain A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. When you no longer need it, you must relinquish ownership of an object you own You relinquish ownership of an object by sending it a release message or an autorelease message. You must not relinquish ownership of an object you do not own This is just corollary of the previous policy rules, stated explicitly. 7

Simple Example The Person object is created using the alloc method, so it is subsequently sent a release message when it is no longer needed. The person s name is not retrieved using any of the owning methods, so it is not sent a release message. { } Person *aperson = [[Person alloc] init]; //... NSString *name = aperson.fullname; //... [aperson release]; 8

Send a Deferred Release You use autorelease when you need to send a deferred release message typically when returning an object from a method. You own the string returned by alloc. To abide by the memory management rules, you must relinquish ownership of the string before you lose the reference to it. If you use release, however, the string will be deallocated before it is returned (and the method would return an invalid object). Using autorelease, you signify that you want to relinquish ownership, but you allow the caller of the method to use the returned string before it is deallocated. - (NSString *)fullname { NSString *string = [[[NSString alloc] initwithformat:@"%@ %@", self.firstname, self.lastname] autorelease]; return string; } 9

Example You could also implement the fullname method like this: - (NSString *)fullname { NSString *string = [NSString stringwithformat:@"%@ %@", self.firstname, self.lastname]; return string; } Following the basic rules, you don t own the string returned by stringwithformat:, so you can safely return the string from the method. 10

Objects Returned by Reference You don't own objects returned by reference Some methods in Cocoa specify that an object is returned by reference (that is, they take an argument of type ClassName ** or id *). A common pattern is to use an NSError object that contains information about an error if one occurs. You do not create the NSError object, so you do not own it. There is no need to release it. NSString *filename = <#Get a file name#>; NSError *error; NSString *string = [[NSString alloc] initwithcontentsoffile:filename encoding:nsutf8stringencoding error:&error]; if (string == nil) { // Deal with error... } //... [string release]; 11

Relinquish Ownership of Objects The NSObject class defines a method, dealloc, that is invoked automatically when an object has no owners and its memory is reclaimed in Cocoa terminology it is freed or deallocated. The role of the dealloc method is to free the object's own memory, and to dispose of any resources it holds, including ownership of any object instance variables. 12

Example of dealloc @interface Person : NSObject @property (retain) NSString *firstname; @property (retain) NSString *lastname; @property (assign, readonly) NSString *fullname; @end @implementation Person //... - (void)dealloc [_firstname release]; [_lastname release]; [super dealloc]; } @end Never invoke another object s dealloc method directly. You must invoke the superclass s implementation at the end of your implementation. 13

Core Foundation Core Foundation uses similar but different rules There are similar memory management rules for Core Foundation objects https://developer.apple.com/library/ios/documentation /CoreFoundation/Conceptual/CFMemoryMgmt/CFMe morymgmt.html#//apple_ref/doc/uid/10000127i The naming conventions for Cocoa and Core Foundation, however, are different. In particular, Core Foundation s Create Rule does not apply to methods that return Objective-C objects. 14

Practical Memory Management Use accessor methods to make memory management easier Use accessor methods to set property values Don t use accessor methods in initializer methods and dealloc Use weak references to avoid retain cycles Avoid causing deallocation of objects you re using Don t use dealloc to manage scarce resources Collections own the objects they contain Ownership policy is implemented using retain counts 15

Ownership Policy The ownership policy is implemented through reference counting typically called retain count after the retain method. Each object has a retain count. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at the end of the current autorelease pool block. If an object s retain count is reduced to zero, it is deallocated. 16

MRR Summary Basically works like this: If you need to keep an object around you need to retain it, unless it already was retained for you. If you want to stop using an object you need to release it, unless it was already released for you (with autorelease). The principles of manual memory management aren t hard but it s very easy to make a mistake, and these small mistakes can have dire consequences. Either your app will crash at some point because you ve released an object too often and your variables are pointing at data that is no longer valid, or you ll run out of memory because you don t release objects enough and they stick around forever. The static analyzer from Xcode is a great help in finding these kinds of problems but ARC goes a step further. 17

ARC ARC is a feature of the LLVM 3.0 compiler and it completely does away with the manual memory management that all ios developers love to hate. Using ARC in your own projects is extremely simple. You keep programming as usual, except that you no longer call retain, release and autorelease. With Automatic Reference Counting enabled, the compiler will automatically insert retain, release and autorelease in the correct places in your program. You no longer have to worry about any of this, because the compiler does it for you. 18

ARC It is important to realize that ARC is a feature of the Objective-C compiler and therefore all the ARC stuff happens when you build your app. ARC is not a runtime feature (except for one small part, the weak pointer system), nor is it *garbage collection* that you may know from other languages. All that ARC does is insert retains and releases into your code when it compiles it, exactly where you would have or at least should have put them yourself. That makes ARC just as fast as manually managed code, and sometimes even a bit faster because it can perform certain optimizations under the hood. 19

Pointers Keep Objects Alive The new rules you have to learn for ARC are quite simple. With manual memory management you needed to retain an object to keep it alive. That is no longer necessary, all you have to do is make a pointer to the object. As long as there is a variable pointing to an object, that object stays in memory. When the pointer gets a new value or ceases to exist, the associated object is released. This is true for all variables: instance variables, synthesized properties, and even local variables. 20

ARC Limitations Automatic Reference Counting also has a few limitations. For starters, ARC only works on Objective-C objects. If your app uses Core Foundation or malloc() and free(), then you re still responsible for doing the memory management there. In addition, certain language rules have been made stricter in order to make sure ARC can always do its job properly. 21

ARC Just because ARC takes care of doing retain and release for you in the proper places, doesn t mean you can completely forget about memory management altogether. Because strong pointers keep objects alive, there are still situations where you will need to set these pointers to nil by hand, or your app might run out of available memory. If you keep holding on to all the objects you ve ever created, then ARC will never be able to release them. Therefore, whenever you create a new object, you still need to think about who owns it and how long the object should stay in existence. 22

Automatic Conversion There are three things you can do to make your app ARC-compatible: 1. Xcode has an automatic conversion tool that can migrate your source files. 2. You can convert the files by hand. 3. You can disable ARC for source files that you do not want to convert. This is useful for third-party libraries that you don t feel like messing with. 23

Switch to ARC ARC is a feature of the new LLVM 3.0 compiler. Your existing projects most likely use the older GCC 4.2 or LLVM-GCC compilers, so it s a good idea to switch the project to the new compiler first and see if it compiles cleanly in non-arc mode. Go to the Project Settings screen, select the Artists target and under Build Settings type compiler into the search box. This will filter the list to bring up just the compiler options Click on the Compiler for C/C++/Objective-C option to change it to Apple LLVM compiler 3.0 24

Switch to ARC Still in the Build Settings screen, switch to All to see all the available settings (instead of Basic, which only shows the most-often used settings). Search for automatic and set the Objective-C Automatic Reference Counting option to Yes. This is a project-wide flag that tells Xcode that you wish to compile all of the source files in your project using the ARC compiler. From Xcode s menu, choose Edit\Refactor\Convert to Objective-C ARC. 25

Review of Properties Properties manage an object s internal data A property s data is stored in an instance variable or ivar Xcode generated these variables automatically The property accesses the ivar via getter/setter methods (aka accessors) Put @property in front of the declaration of the ivar We access properties using the self keyword 26

Encapsulation Getter and setter methods Prevent direct access to object data Allow a class to respond to data changes Enable inheritance and overriding Properties Provide automatic encapsulation Enable Key-Value Observing in Cocoa Manage Memory http://stackoverflow.com/questions/1568091/ why-user-getters-and-setters 27

Placement Put in the interface file (.h) to make them public to other classes // USCViewController.h @interface USCViewController : UIViewController @end In the class extension in the implementation file (.m) // USCViewController.m @interface USCViewController () @end 28

Examples // Primitive type, read-write by default @property int age; // Primitive type, read-only @property (readonly) BOOL canlegallyvote; // IBOutlets @property (weak, nonatomic) IBOutlet UITextField *nametf; @property (weak, nonatomic) IBOutlet UILabel *messagelabel; // Objects @property (strong, nonatomic) NSString *name; // Objects, create only a getter @property (readonly) UIView *rootview; 29

Property Attributes @property (strong, nonatomic) NSDate *launchtime; Memory Properties Readable Properties Method Name Properties Threading Properties strong weak copy assign readonly readwrite getter setter nonatomic atomic Setter retains the new value (default under ARC) Assignment doesn't affect object's lifespan Setter makes a copy of the new value For primitives (preceded weak for objects) Only a getter is generated Getter and setter methods generated (default) The method name used for the getter The method name used for the setter Doesn't ensure multi-thread safety of get/set Makes get/set multi-thread safe (default) 30

Attributes IBOutlets (Interface Builder components) Use (weak, nonatomic) Class ivars (instance variables) Use (strong, nonatomic) for mobile // IBOutlets @property (weak, nonatomic) IBOutlet UITextField *nametf; @property (weak, nonatomic) IBOutlet UILabel *messagelabel; // Objects @property (strong, nonatomic) NSString *name; @property (strong, nonatomic) NSDate *launchtime; 31

Weak References Retaining an object creates a strong reference to that object. An object cannot be deallocated until all of its strong references are released. A problem, known as a retain cycle, can therefore arise if two objects may have cyclical references that is, they have a strong reference to each other (either directly, or through a chain of other objects each with a strong reference to the next leading back to the first). 32

Example The Document object has a Page object for each page in the document. Each Page object has a property that keeps track of which document it is in. If the Document object has a strong reference to the Page object and the Page object has a strong reference to the Document object, neither object can ever be deallocated. The Document s reference count cannot become zero until the Page object is released, and the Page object won t be released until the Document object is deallocated. 33

Example The solution to the problem of retain cycles is to use weak references. A weak reference is a non-owning relationship where the source object does not retain the object to which it has a reference. To keep the object graph intact, however, there must be strong references somewhere (if there were only weak references, then the pages and paragraphs might not have any owners and so would be deallocated). Cocoa establishes a convention, therefore, that a parent object should maintain strong references to its children, and that the children should have weak references to their parents. 34

Memory Management Efficient memory management is an important aspect of writing high performance code in both OS X and ios. Minimizing memory usage not only decreases your application s memory footprint, it can also reduce the amount of CPU time it consumes. Both OS X and ios include a fully-integrated virtual memory system that you cannot turn off; it is always on. Both systems also provide up to 4 gigabytes of addressable space per 32-bit process. 35

Virtual Memory System In iphone applications, read-only data that is already on the disk (such as code pages) is simply removed from memory and reloaded from disk as needed. Writable data is never removed from memory by the operating system. Instead, if the amount of free memory drops below a certain threshold, the system asks the running applications to free up memory voluntarily to make room for new data. Applications that fail to free up enough memory are terminated. 36

Tips for Allocating Memory Memory is an important resource for your application so it s important to think about how your application will use memory and what might be the most efficient allocation approaches. Most applications do not need to do anything special; they can simply allocate objects or memory blocks as needed and not see any performance degradation. For applications that use large amount of memory, however, carefully planning out your memory allocation strategy could make a big difference. 37

Improve Memory-Related Performance Besides allocating the right amount of memory for a given operation, there are other ways to improve the efficiency of your program's memory usage. Tips: Defer your memory allocations Initialize memory block efficiently Reuse temporary memory buffers Free unused memory 38

Good Practices Prevent Problems There are two main kinds of problems that result from incorrect memory management: Freeing or overwriting data that is still in use This causes memory corruption, and typically results in your application crashing, or worse, corrupted user data. Not freeing data that is no longer in use causes memory leaks A memory leak is where allocated memory is not freed, even though it is never used again. Leaks cause your application to use ever-increasing amounts of memory, which in turn may result in poor system performance or your application being terminated. 39

Good Practices Prevent Problems Thinking about memory management from the perspective of reference counting, however, is frequently counterproductive, because you tend to consider memory management in terms of the implementation details rather than in terms of your actual goals. Instead, you should think of memory management from the perspective of object ownership and object graphs. Cocoa uses a straightforward naming convention to indicate when you own an object returned by a method. 40

Resources http://www.raywenderlich.com/5677/beginning-arc-inios-5-part-1 https://developer.apple.com/library/ios/documentation /general/conceptual/devpediacocoacore/memorymanagement.html https://mobileappmastery.com/objective-c-memorymanagement/ https://developer.apple.com/library/ios/documentation /Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.h tml https://developer.apple.com/library/mac/documentatio n/performance/conceptual/managingmemory/articles/ MemoryAlloc.html 41