SlideShare a Scribd company logo
1 of 27
Download to read offline
MEMORY MANAGEMENT 

ON IOS
AGENDA
Reference Count Based Memory Management
Manual Reference Counting
Automatic Reference Counting (ARC)
ARC vs. Tracing Garbage Collectors
Gotchas
REFERENCE COUNT BASED
MEMORY MANAGEMENT
WHY DO WE NEED MEMORY
MANAGEMENT?
func createPerson() {
var p = Person()
}
main
createPerson()
Person
Stack Heap
WHY DO WE NEED MEMORY MANAGEMENT?
class Business {
var owner: Person
init() {
self.owner = Person()
}
}
1
1
2
…
…
Person
Stack Heap
Business
ViewController
Reference Count
MANUAL REFERENCE
COUNTING
MANUAL REFERENCE COUNTING
Objects are held in memory as long as they have a retain
count that is larger than 0
MANUAL REFERENCE COUNTING
Retain count of an object is mainly determined by calls to three
different methods: retain, release, autorelease
Additionally objects you create have a retain count of 1 - in Obj-
C this is indicated by calling any method named “alloc”, “new”,
“copy”, or “mutableCopy”
MANUAL REFERENCE COUNTING
- (void)createPerson {
Person *person = [[[Person alloc] init] autorelease];
return person;
}
+1 -1
MANUAL REFERENCE COUNTING
@interface Business : NSObject
@property (nonatomic, strong) Person *name;
@end
+1 -1- (void)createOwner {
self.owner = [[[Person alloc] init] autorelease];
}
+1
- (void)freeOwner {
self.owner = nil;
}
-1
AUTOMATIC REFERENCE
COUNTING (ARC)
AUTOMATIC REFERENCE
COUNTING (ARC)
No manual calls to retain, release, autorelease
anymore
Memory Management calls are inserted at compile time
Think in strong, weak and unowned references
AUTOMATIC REFERENCE
COUNTING
class Business {
var owner: Person
weak var building: Building?
init() {
self.owner = Person()
self.building = Building()
}
}
+1
+0
ARC VS. TRACING GARBAGE
COLLECTORS
ARC VS. TRACING GARBAGE
COLLECTORS
Tracing Garage Collectors are used in many higher level languages
such as C#, Java and Ruby (Python uses reference counts)
ARC VS. TRACING GARBAGE
COLLECTORS
Tracing GCs collect unreferenced objects after certain time periods at
runtime, typically work in two phases:
1. Mark all objects that are reachable from a root object
2. Delete all objects that are not reachable from a root object
GOTCHAS
GOTCHAS
Pure reference counting garbage collection mechanisms
cannot detect retain cycles!
Retain cycles occur when multiple objects reference each
other strongly, but aren’t strongly referenced by any root
object
GOTCHAS
Retain cycles created by the usage of closures:

class UserViewController: UIViewController {
var callback: UserDetailsCallback?
override func viewDidAppear(animated: Bool) {
callback = { user in
self.showUser(user)
}
}
func showUser(user: User?) {
//...
}
}
UserViewController
UserDetailsCallback+1
+1
GOTCHAS
Fix retain cycles using weak/unowned:

class UserViewController: UIViewController {
var callback: UserDetailsCallback?
override func viewDidAppear(animated: Bool) {
callback = { [unowned self] user in
self.showUser(user)
}
}
func showUser(user: User?) {
//...
}
}
UserViewController
UserDetailsCallback+1
+0
GOTCHAS
Retain cycles created by the usage of strong delegates:

protocol UserViewDelegate {}
class UserView {
var delegate: UserViewDelegate?
}
class UserViewController: UIViewController {
var userView: UserView = UserView()
func viewDidLoad() {
super.viewDidLoad()
userView.delegate = self
}
}
UserViewController
UserView+1
+1
GOTCHAS
Fix using a weak reference to the delegate:

protocol UserViewDelegate {}
class UserView {
weak var delegate: UserViewDelegate?
}
class UserViewController: UIViewController {
var userView: UserView = UserView()
func viewDidLoad() {
super.viewDidLoad()
userView.delegate = self
}
}
UserViewController
UserView+1
+0
SUMMARY
SUMMARY
Swift’s memory management model is based on reference
counting
With ARC reference counting works semi-automatically, retain
and release calls are inferred from memory management
specifiers (strong, weak, unowned)
Some types of memory issues that can be detected by tracing
GCs cannot be detected by reference counting, e.g. retain
cycles
ADDITIONAL RESOURCES
ADDITIONAL RESOURCES
Apple: Advanced Memory Management
Programming Guide
iOS Memory Management Using Autorelease
Wikipedia: Tracing Garbage Collectors

More Related Content

What's hot

[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기NHN FORWARD
 
Android animation
Android animationAndroid animation
Android animationKrazy Koder
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK toolsHaribabu Nandyal Padmanaban
 
Event driven architecture with Kafka
Event driven architecture with KafkaEvent driven architecture with Kafka
Event driven architecture with KafkaFlorence Next
 
Getting started with Docker
Getting started with DockerGetting started with Docker
Getting started with DockerRavindu Fernando
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in DockerDocker, Inc.
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
Migration from SQL to MongoDB - A Case Study at TheKnot.com
Migration from SQL to MongoDB - A Case Study at TheKnot.com Migration from SQL to MongoDB - A Case Study at TheKnot.com
Migration from SQL to MongoDB - A Case Study at TheKnot.com MongoDB
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
Android application structure
Android application structureAndroid application structure
Android application structureAlexey Ustenko
 

What's hot (20)

Android MVVM
Android MVVMAndroid MVVM
Android MVVM
 
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
[2019] PAYCO 쇼핑 마이크로서비스 아키텍처(MSA) 전환기
 
Google android Activity lifecycle
Google android Activity lifecycle Google android Activity lifecycle
Google android Activity lifecycle
 
Android animation
Android animationAndroid animation
Android animation
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Event driven architecture with Kafka
Event driven architecture with KafkaEvent driven architecture with Kafka
Event driven architecture with Kafka
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Getting started with Docker
Getting started with DockerGetting started with Docker
Getting started with Docker
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in Docker
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Reversing Google Protobuf protocol
Reversing Google Protobuf protocolReversing Google Protobuf protocol
Reversing Google Protobuf protocol
 
Docker
DockerDocker
Docker
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Migration from SQL to MongoDB - A Case Study at TheKnot.com
Migration from SQL to MongoDB - A Case Study at TheKnot.com Migration from SQL to MongoDB - A Case Study at TheKnot.com
Migration from SQL to MongoDB - A Case Study at TheKnot.com
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Android application structure
Android application structureAndroid application structure
Android application structure
 

Viewers also liked

Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOSMake School
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C InteropMake School
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project InfrastructureMake School
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOSMake School
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOSMake School
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOSMake School
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in SwiftMake School
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewMake School
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application ArchitectureMake School
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout OverviewMake School
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with FlaskMake School
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOSMake School
 

Viewers also liked (20)

Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection View
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOS
 

Similar to Memory Management on iOS

Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView ScrollingAndrea Prearo
 
20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-finalDavid Lapsley
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)David Pichsenmeister
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingMitinPavel
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective CNeha Gupta
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components WorkshopGordon Bockus
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsUlf Wendel
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJSBrajesh Yadav
 
Smooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionViewSmooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionViewAndrea Prearo
 
Interpreter implementation of advice weaving
Interpreter implementation of advice weavingInterpreter implementation of advice weaving
Interpreter implementation of advice weavinginaseer
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swiftYusuke Kita
 

Similar to Memory Management on iOS (20)

Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
 
20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event Sourcing
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components Workshop
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective C
 
Lightning Components Workshop
Lightning Components WorkshopLightning Components Workshop
Lightning Components Workshop
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Controller
ControllerController
Controller
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
 
Smooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionViewSmooth scrolling in UITableView and UICollectionView
Smooth scrolling in UITableView and UICollectionView
 
Interpreter implementation of advice weaving
Interpreter implementation of advice weavingInterpreter implementation of advice weaving
Interpreter implementation of advice weaving
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

Memory Management on iOS

  • 1.
  • 3. AGENDA Reference Count Based Memory Management Manual Reference Counting Automatic Reference Counting (ARC) ARC vs. Tracing Garbage Collectors Gotchas
  • 5. WHY DO WE NEED MEMORY MANAGEMENT? func createPerson() { var p = Person() } main createPerson() Person Stack Heap
  • 6. WHY DO WE NEED MEMORY MANAGEMENT? class Business { var owner: Person init() { self.owner = Person() } } 1 1 2 … … Person Stack Heap Business ViewController Reference Count
  • 8. MANUAL REFERENCE COUNTING Objects are held in memory as long as they have a retain count that is larger than 0
  • 9. MANUAL REFERENCE COUNTING Retain count of an object is mainly determined by calls to three different methods: retain, release, autorelease Additionally objects you create have a retain count of 1 - in Obj- C this is indicated by calling any method named “alloc”, “new”, “copy”, or “mutableCopy”
  • 10. MANUAL REFERENCE COUNTING - (void)createPerson { Person *person = [[[Person alloc] init] autorelease]; return person; } +1 -1
  • 11. MANUAL REFERENCE COUNTING @interface Business : NSObject @property (nonatomic, strong) Person *name; @end +1 -1- (void)createOwner { self.owner = [[[Person alloc] init] autorelease]; } +1 - (void)freeOwner { self.owner = nil; } -1
  • 13. AUTOMATIC REFERENCE COUNTING (ARC) No manual calls to retain, release, autorelease anymore Memory Management calls are inserted at compile time Think in strong, weak and unowned references
  • 14. AUTOMATIC REFERENCE COUNTING class Business { var owner: Person weak var building: Building? init() { self.owner = Person() self.building = Building() } } +1 +0
  • 15. ARC VS. TRACING GARBAGE COLLECTORS
  • 16. ARC VS. TRACING GARBAGE COLLECTORS Tracing Garage Collectors are used in many higher level languages such as C#, Java and Ruby (Python uses reference counts)
  • 17. ARC VS. TRACING GARBAGE COLLECTORS Tracing GCs collect unreferenced objects after certain time periods at runtime, typically work in two phases: 1. Mark all objects that are reachable from a root object 2. Delete all objects that are not reachable from a root object
  • 19. GOTCHAS Pure reference counting garbage collection mechanisms cannot detect retain cycles! Retain cycles occur when multiple objects reference each other strongly, but aren’t strongly referenced by any root object
  • 20. GOTCHAS Retain cycles created by the usage of closures:
 class UserViewController: UIViewController { var callback: UserDetailsCallback? override func viewDidAppear(animated: Bool) { callback = { user in self.showUser(user) } } func showUser(user: User?) { //... } } UserViewController UserDetailsCallback+1 +1
  • 21. GOTCHAS Fix retain cycles using weak/unowned:
 class UserViewController: UIViewController { var callback: UserDetailsCallback? override func viewDidAppear(animated: Bool) { callback = { [unowned self] user in self.showUser(user) } } func showUser(user: User?) { //... } } UserViewController UserDetailsCallback+1 +0
  • 22. GOTCHAS Retain cycles created by the usage of strong delegates:
 protocol UserViewDelegate {} class UserView { var delegate: UserViewDelegate? } class UserViewController: UIViewController { var userView: UserView = UserView() func viewDidLoad() { super.viewDidLoad() userView.delegate = self } } UserViewController UserView+1 +1
  • 23. GOTCHAS Fix using a weak reference to the delegate:
 protocol UserViewDelegate {} class UserView { weak var delegate: UserViewDelegate? } class UserViewController: UIViewController { var userView: UserView = UserView() func viewDidLoad() { super.viewDidLoad() userView.delegate = self } } UserViewController UserView+1 +0
  • 25. SUMMARY Swift’s memory management model is based on reference counting With ARC reference counting works semi-automatically, retain and release calls are inferred from memory management specifiers (strong, weak, unowned) Some types of memory issues that can be detected by tracing GCs cannot be detected by reference counting, e.g. retain cycles
  • 27. ADDITIONAL RESOURCES Apple: Advanced Memory Management Programming Guide iOS Memory Management Using Autorelease Wikipedia: Tracing Garbage Collectors