SlideShare uma empresa Scribd logo
1 de 19
Memory Management in iOS
COMPILED BY: ASIM RAIS SIDDIQUI
Table of Contents
 Overview
 Reference counting in Objective C
 Taking ownership of an object
 The Four Basic Rules
 ARC
Overview
 You manage memory in iOS4 and below
 iOS5 and above –Automaticc Reference Counting (ARC) available
Reference Counting in Objective‐C
 When an object is created, it has a reference count of 1. The
creator is the owner.
 Every time, a new owner is added, the reference count increases by
1
 Every time, a owner relinquishes control , the reference count
decreases by 1
 When reference count is 0, runtime destroys the object by calling
dealloc() on it.
– You never call dealloc() directly. release does it automatically
Taking ownership of an object
 Create an object
– alloc, new, copy!
 Using “retain”
– Retain the object to ensure it is not deallocated elsewhere
 Strong References
– Object not freed as long as there is a strong reference to it. Use
“retain”
@property (retain) id myProperty; // iOS <= 4.3
@property (strong) id myProperty; // iOS 5+
Relinquishing ownership of an
Object
 Explicitly using release
– Object deallocated as soon as reference count is 0 • Put it in an
autorelease pool.
 System takes care of deallocating unreferenced objects
periodically from autorelease pool at some later time
The Four Basic Rules
 There are only 4 basic rules when it comes to memory management
in Objective-C:
1. If you own it, release it.
2. If you don’t own it, don’t release it.
3. Override dealloc in your classes to release the fields that you own.
4. Never call dealloc directly.
 That’s it. The first two are the most important and we’ll get into the
basics of object ownership next.
How easy is that? I can’t even think
of anything more to write about
this, it’s that simple. But to reiterate:
You own it if you alloc it.
You own it if you copy it.
You own it if you new it. (New is
simply a shortcut for alloc/init).
In the above example, our SomeObject has two fields: things and someOtherThings. You can see in our init method
that we create the objects and assign them to our properties. For things, because we are using [NSMutableArray
arrayWithObjects:], we have to call retain. Remember, we didn’t alloc, copy or new, instead we called a
convenience method that returns an autoreleased object that we must explicitly retain. What is autorelease you
might be asking? I’ll explain in the next part, but for now all you have to remember is the basics of object ownership
described above.
In the [dealloc] method you’ll see that we are releasing the objects we created. Nothing more, nothing less.
Properties
 There is really only two rules:
 If you retain or copy your property, you need to set it to nil in your
dealloc.
 If you initialize the property during init, autorelease it.
The title property we are calling a convenience method on NSString that returns an autoreleased object, so we don’t have to do a
thing. For subtitle, we are allocating a new NSString ourselves, therefore we need to autorelease it. The reason being is that when the
value is assigned to the property, the retain count is incremented by 1, so without the autorelease, that object will maintain a retain
count of 2 (one for the alloc/init and another for the assignment to the property). With a retain count of 2, the object will never be
released and you’ll leak memory.
Autorelease?
 Ok, I totally lied as there is one more complicated aspect to this
whole thing, and that complexity comes in the form of Autorelease
Pools. The heck is that? Autorelease pools maintain a list of objects
that will be sent release messages when those pools are destroyed.
You really needn’t worry about when all of that happens, but rest
assured that your autorelease objects are, if everything is done
correctly, being released without your explicit telling it to do so.
 Following our rules of object ownership, one has to wonder what
happens to objects that are returned from methods. Who owns
those? This is where autorelease and autorelease pools come in to
play. For example:
 Notice the autorelease message
at the end. What happens
when autorelease is called, the
object in question is added to
an autorelease pool so that it
will receive a release message
when the pool is destroyed. The
caller needn’t have to worry
about it, nor does the callee.
 Autorelease pools can be
nested, too. This is great for
situations where you are
creating thousands upon
thousands of temporary objects
and want to keep your
maximum memory footprint slim
and tight. Also, if you are doing
threaded work, anytime you
create a new thread, you’ll
have to create an autorelease
pool for that thread.
Automatic Reference Counting
 Introduced in iOS5
 You don’t need to specify retain/release
 Compiler inserts the retain/release code for you
 ARC frees objects as soon as all strong references to it go away
 It’s not Garbage CollecBon
Automatic Reference Counting
 If you are working with existing code, you can convert it to use ARC
by going to the Edit menu, and under the Refactor sub-menu you
will see “Convert to Objective-C ARC” as a choice. There is also a
compiler flag (-fobjc-arc) to enable ARC. You can also go into the
build options for a project (select the project, go to advanced build
options, and it is near the bottom)
 Within your code, you can now use the “strong” and “weak”
keywords in your object instantiation. With these, the compiler
understands how to handle the memory for the object. What’s the
difference? From the book Learning iPad Programming by Kirby
Turner and Tom Harrington (the book I have been using to learn iOS
development):
 A strong property is claiming “ownership,” and its object is
automatically released when the object is no longer referenced. A
weak property does not extend the lifetime of the object. In other
words, it does not assume ownership, so it is possible that the object
is released while the property has a reference to it. However, weak
properties are automatically set to nil when the object is released.

Mais conteúdo relacionado

Mais procurados

Android activity
Android activityAndroid activity
Android activityKrazy Koder
 
Deadlock in Operating System
Deadlock in Operating SystemDeadlock in Operating System
Deadlock in Operating SystemAUST
 
An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...William Liang
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linuxMazenetsolution
 
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)William Liang
 
Android Binder IPC for Linux
Android Binder IPC for LinuxAndroid Binder IPC for Linux
Android Binder IPC for LinuxYu-Hsin Hung
 
Evolution of android operating system
Evolution of android operating systemEvolution of android operating system
Evolution of android operating systemMd. Abdullah Al Maruf
 
Workshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityWorkshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityAndrew Case
 
Description of GRUB 2
Description of GRUB 2Description of GRUB 2
Description of GRUB 2iamumr
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecturedeepakshare
 
Supporting multiple screens on android
Supporting multiple screens on androidSupporting multiple screens on android
Supporting multiple screens on androidLi SUN
 

Mais procurados (20)

Android activity
Android activityAndroid activity
Android activity
 
Embedded Android : System Development - Part III
Embedded Android : System Development - Part IIIEmbedded Android : System Development - Part III
Embedded Android : System Development - Part III
 
Deadlock in Operating System
Deadlock in Operating SystemDeadlock in Operating System
Deadlock in Operating System
 
An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linux
 
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
 
Linux file system
Linux file systemLinux file system
Linux file system
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
Android Binder IPC for Linux
Android Binder IPC for LinuxAndroid Binder IPC for Linux
Android Binder IPC for Linux
 
Memory model
Memory modelMemory model
Memory model
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
 
Evolution of android operating system
Evolution of android operating systemEvolution of android operating system
Evolution of android operating system
 
Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0
 
Workshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityWorkshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with Volatility
 
Windows kernel
Windows kernelWindows kernel
Windows kernel
 
Description of GRUB 2
Description of GRUB 2Description of GRUB 2
Description of GRUB 2
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
 
Android Things : Building Embedded Devices
Android Things : Building Embedded DevicesAndroid Things : Building Embedded Devices
Android Things : Building Embedded Devices
 
Supporting multiple screens on android
Supporting multiple screens on androidSupporting multiple screens on android
Supporting multiple screens on android
 

Destaque

iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management BasicsBilue
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective CNeha Gupta
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
Memory management in iOS.
Memory management in iOS.Memory management in iOS.
Memory management in iOS.HSIEH CHING-FAN
 
Apple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemApple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemDhruv Patel
 
Apple iOS Introduction
Apple iOS IntroductionApple iOS Introduction
Apple iOS IntroductionPratik Vyas
 
Memory Management In Swift
Memory Management In SwiftMemory Management In Swift
Memory Management In SwiftHossam Ghareeb
 
Property and MM with ARC in Objective-C
Property and MM with ARC in Objective-CProperty and MM with ARC in Objective-C
Property and MM with ARC in Objective-CYo Yo Chen
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Countingpragmamark
 
Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotionMichael Denomy
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingGiuseppe Arici
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touchmobiledeveloperpl
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーSatoshi Asano
 
Unix Process management
Unix Process managementUnix Process management
Unix Process managementWave Digitech
 

Destaque (20)

iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management Basics
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective C
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Android & IOS
Android & IOSAndroid & IOS
Android & IOS
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
Memory management in iOS.
Memory management in iOS.Memory management in iOS.
Memory management in iOS.
 
Apple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemApple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating system
 
Apple iOS Introduction
Apple iOS IntroductionApple iOS Introduction
Apple iOS Introduction
 
Objective C Memory Management
Objective C Memory ManagementObjective C Memory Management
Objective C Memory Management
 
Memory Management In Swift
Memory Management In SwiftMemory Management In Swift
Memory Management In Swift
 
Property and MM with ARC in Objective-C
Property and MM with ARC in Objective-CProperty and MM with ARC in Objective-C
Property and MM with ARC in Objective-C
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Ios - Introduction to memory management
Ios - Introduction to memory managementIos - Introduction to memory management
Ios - Introduction to memory management
 
Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotion
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touch
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
 
Unix Process management
Unix Process managementUnix Process management
Unix Process management
 
12 deadlock concept
12 deadlock concept12 deadlock concept
12 deadlock concept
 
iOS Ecosystem
iOS EcosystemiOS Ecosystem
iOS Ecosystem
 

Semelhante a iOS Memory Management

[Objective-C] Objective-C의 메모리 관리 방법
[Objective-C] Objective-C의 메모리 관리 방법[Objective-C] Objective-C의 메모리 관리 방법
[Objective-C] Objective-C의 메모리 관리 방법Theodore(Yongbin) Cha
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad ideaPVS-Studio
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep DiveManish Jangir
 
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15Raunak Talwar
 
Method Swizzling with Objective-C
Method Swizzling with Objective-CMethod Swizzling with Objective-C
Method Swizzling with Objective-CAdamFallon4
 
Garbage collector complete information
Garbage collector complete informationGarbage collector complete information
Garbage collector complete informationMubarak Hussain
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureManish Jangir
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bagJacob Green
 
01class_object_references & 02Generation_GC.pptx
01class_object_references & 02Generation_GC.pptx01class_object_references & 02Generation_GC.pptx
01class_object_references & 02Generation_GC.pptxssuser95922e
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionSomya Bagai
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programmingSujith Krishnan
 

Semelhante a iOS Memory Management (20)

Lecture 3-ARC
Lecture 3-ARCLecture 3-ARC
Lecture 3-ARC
 
[Objective-C] Objective-C의 메모리 관리 방법
[Objective-C] Objective-C의 메모리 관리 방법[Objective-C] Objective-C의 메모리 관리 방법
[Objective-C] Objective-C의 메모리 관리 방법
 
Memory management
Memory managementMemory management
Memory management
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
 
Memory management ARC
Memory management ARCMemory management ARC
Memory management ARC
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15
Avoid memory leaks using unit tests - Swift Delhi Meetup - Chapter 15
 
Method Swizzling with Objective-C
Method Swizzling with Objective-CMethod Swizzling with Objective-C
Method Swizzling with Objective-C
 
Garbage collector complete information
Garbage collector complete informationGarbage collector complete information
Garbage collector complete information
 
Ios development
Ios developmentIos development
Ios development
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
 
01class_object_references & 02Generation_GC.pptx
01class_object_references & 02Generation_GC.pptx01class_object_references & 02Generation_GC.pptx
01class_object_references & 02Generation_GC.pptx
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
13 life and scope
13 life and scope13 life and scope
13 life and scope
 
About Python
About PythonAbout Python
About Python
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programming
 

Mais de Asim Rais Siddiqui

Understanding Blockchain Technology
Understanding Blockchain TechnologyUnderstanding Blockchain Technology
Understanding Blockchain TechnologyAsim Rais Siddiqui
 
IoT Development - Opportunities and Challenges
IoT Development - Opportunities and ChallengesIoT Development - Opportunities and Challenges
IoT Development - Opportunities and ChallengesAsim Rais Siddiqui
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsAsim Rais Siddiqui
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS DevelopmentAsim Rais Siddiqui
 

Mais de Asim Rais Siddiqui (8)

Understanding Blockchain Technology
Understanding Blockchain TechnologyUnderstanding Blockchain Technology
Understanding Blockchain Technology
 
IoT Development - Opportunities and Challenges
IoT Development - Opportunities and ChallengesIoT Development - Opportunities and Challenges
IoT Development - Opportunities and Challenges
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI Components
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
iOS Development (Part 1)
iOS Development (Part 1)iOS Development (Part 1)
iOS Development (Part 1)
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS Development
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

iOS Memory Management

  • 1. Memory Management in iOS COMPILED BY: ASIM RAIS SIDDIQUI
  • 2. Table of Contents  Overview  Reference counting in Objective C  Taking ownership of an object  The Four Basic Rules  ARC
  • 3. Overview  You manage memory in iOS4 and below  iOS5 and above –Automaticc Reference Counting (ARC) available
  • 4. Reference Counting in Objective‐C  When an object is created, it has a reference count of 1. The creator is the owner.  Every time, a new owner is added, the reference count increases by 1  Every time, a owner relinquishes control , the reference count decreases by 1  When reference count is 0, runtime destroys the object by calling dealloc() on it. – You never call dealloc() directly. release does it automatically
  • 5.
  • 6. Taking ownership of an object  Create an object – alloc, new, copy!  Using “retain” – Retain the object to ensure it is not deallocated elsewhere  Strong References – Object not freed as long as there is a strong reference to it. Use “retain” @property (retain) id myProperty; // iOS <= 4.3 @property (strong) id myProperty; // iOS 5+
  • 7. Relinquishing ownership of an Object  Explicitly using release – Object deallocated as soon as reference count is 0 • Put it in an autorelease pool.  System takes care of deallocating unreferenced objects periodically from autorelease pool at some later time
  • 8. The Four Basic Rules  There are only 4 basic rules when it comes to memory management in Objective-C: 1. If you own it, release it. 2. If you don’t own it, don’t release it. 3. Override dealloc in your classes to release the fields that you own. 4. Never call dealloc directly.  That’s it. The first two are the most important and we’ll get into the basics of object ownership next.
  • 9. How easy is that? I can’t even think of anything more to write about this, it’s that simple. But to reiterate: You own it if you alloc it. You own it if you copy it. You own it if you new it. (New is simply a shortcut for alloc/init).
  • 10.
  • 11. In the above example, our SomeObject has two fields: things and someOtherThings. You can see in our init method that we create the objects and assign them to our properties. For things, because we are using [NSMutableArray arrayWithObjects:], we have to call retain. Remember, we didn’t alloc, copy or new, instead we called a convenience method that returns an autoreleased object that we must explicitly retain. What is autorelease you might be asking? I’ll explain in the next part, but for now all you have to remember is the basics of object ownership described above. In the [dealloc] method you’ll see that we are releasing the objects we created. Nothing more, nothing less.
  • 12. Properties  There is really only two rules:  If you retain or copy your property, you need to set it to nil in your dealloc.  If you initialize the property during init, autorelease it.
  • 13. The title property we are calling a convenience method on NSString that returns an autoreleased object, so we don’t have to do a thing. For subtitle, we are allocating a new NSString ourselves, therefore we need to autorelease it. The reason being is that when the value is assigned to the property, the retain count is incremented by 1, so without the autorelease, that object will maintain a retain count of 2 (one for the alloc/init and another for the assignment to the property). With a retain count of 2, the object will never be released and you’ll leak memory.
  • 14. Autorelease?  Ok, I totally lied as there is one more complicated aspect to this whole thing, and that complexity comes in the form of Autorelease Pools. The heck is that? Autorelease pools maintain a list of objects that will be sent release messages when those pools are destroyed. You really needn’t worry about when all of that happens, but rest assured that your autorelease objects are, if everything is done correctly, being released without your explicit telling it to do so.  Following our rules of object ownership, one has to wonder what happens to objects that are returned from methods. Who owns those? This is where autorelease and autorelease pools come in to play. For example:
  • 15.  Notice the autorelease message at the end. What happens when autorelease is called, the object in question is added to an autorelease pool so that it will receive a release message when the pool is destroyed. The caller needn’t have to worry about it, nor does the callee.  Autorelease pools can be nested, too. This is great for situations where you are creating thousands upon thousands of temporary objects and want to keep your maximum memory footprint slim and tight. Also, if you are doing threaded work, anytime you create a new thread, you’ll have to create an autorelease pool for that thread.
  • 16. Automatic Reference Counting  Introduced in iOS5  You don’t need to specify retain/release  Compiler inserts the retain/release code for you  ARC frees objects as soon as all strong references to it go away  It’s not Garbage CollecBon
  • 17. Automatic Reference Counting  If you are working with existing code, you can convert it to use ARC by going to the Edit menu, and under the Refactor sub-menu you will see “Convert to Objective-C ARC” as a choice. There is also a compiler flag (-fobjc-arc) to enable ARC. You can also go into the build options for a project (select the project, go to advanced build options, and it is near the bottom)
  • 18.
  • 19.  Within your code, you can now use the “strong” and “weak” keywords in your object instantiation. With these, the compiler understands how to handle the memory for the object. What’s the difference? From the book Learning iPad Programming by Kirby Turner and Tom Harrington (the book I have been using to learn iOS development):  A strong property is claiming “ownership,” and its object is automatically released when the object is no longer referenced. A weak property does not extend the lifetime of the object. In other words, it does not assume ownership, so it is possible that the object is released while the property has a reference to it. However, weak properties are automatically set to nil when the object is released.