SlideShare a Scribd company logo
1 of 20
MEMORY MANAGEMENT IN OBJECTIVE C 
By: 
Neha Gupta 
Software Engineer, Mindfire Solutions, Noida 
Follow at: 
http://developersarea.wordpress.com/ 
https://www.facebook.com/programmingtipstechniques
MEMORY MANAGEMENT 
- Allocation and Recycling 
When a program requests a block of memory, memory 
manager assigns that block to program. 
When the program no longer need that data, those blocks 
become available for reassignment. 
This task can be done manually (by the programmer) or 
automatically (by the memory manager)
Memory Management in Objective C 
ios 4 and below – Manual memory management 
ios 5 and above – Automatic Reference Counting 
OS X 10.4 and below – Manual memory 
management 
OS X 10.5 – 10.7 – Garbage Collector 
OS X 10.7 – Automatic Reference Counting
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 
alloc - Create an object and claim ownership of it. 
copy - Copy object and claim ownership of it. 
retain - Claim ownership of an existing object. 
You own a object if: 
SomeClass* obj = [[SomeClass alloc]init]; 
SomeClass* obj = [SomeClass copy]; 
SomeClass* obj = [SomeClass new];
Relinquishing ownership of an Object 
release – Relinquishing ownership of an object and 
destroy it immediately. 
autorelease – Relinquishing ownership of an object 
but defer its destruction.
When you forget to balance any alloc, retain & copy 
call with a release or autorelease on same object : 
If you forget to release an object, its underlying 
memory is never freed, resulting in memory leak. 
If you release object too many times, it will result 
into dangling pointer.
The retain method 
@interface MyClass : NSObject 
{ 
NSMutableArray* _values; 
} 
- (NSMutableArray*)values; 
- (void)setValues : (NSMutableArray*)newValues; 
Will create weak reference if implemented as below: 
- (NSMutableArray*)values 
{ 
return _values; 
} 
- (void)setValues : (NSMutableArray*)newValues 
{ 
_values = newValues; 
}
Now in main, 
NSMutableArray* addValues = [[NSMutableArray 
alloc]init]; 
[addValues addObject: @”abcd”]; 
MyClass* class1 = [[MyClass alloc]init]; 
[class1 setValues: addValues]; 
[addValues release]; 
NSLog(@”%@”,[class1 values]); //error, dangling pointer 
Because the objet is already released, class1 object has 
weak reference to array.
Correct way…. 
MyClass needs to claim ownership of the array as : 
- (void)setValues : (NSMutableArray*)newValues 
{ 
_values = [newValues retain] ; //refcount = 2 
} 
This ensures the object wont be released while our 
class object is using it. 
But this code creates another problem…
The retain call isn’t balanced with a release, so we have another 
memory leak. 
Here as soon as we pass another value to setValues: , we cant access 
the old value, which means we can never free it. 
To fix this setValues: needs to call release on the old value 
- (void)setValues : (NSMutableArray*)newValues 
{ 
if(_values == newValues) 
{ 
return; 
} 
NSMutableArray* oldval = _values; 
_values = [newValues retain] ; //refcount = 2 
[oldval release]; 
} 
This is basically what “strong” and “retain” property attributes do.
The copy method.. 
- Creates a brand new instance of the object and 
increments the reference count on that leaving the 
original unaffected.
Autorelease method 
- Relinquishes ownership of an object 
- Doesn’t destroy the object immediately 
- Defer the freeing of memory until later on in the program 
Ex:- 
+(MyClass*) classObj{ 
MyClass* obj = [[MyClass alloc]init]; 
return [obj autorelease]; 
} 
Methods like stringWithFormat: and stringWithString: works 
the same way… 
It waits until the nearest @autoreleasepool{} block after which 
it calls a normal release method on all autorelease objects.
AutoRelease Pools 
Maintains a list of objects that will be sent release 
messages when those pools are destroyed. 
Can be nested 
You should always create a autorelease pool 
whenever you create a new thread.
The dealloc method 
Called right before the object is destroyed, giving you 
a chance to clean up any internal objects. 
Called automatically by runtime. 
You should never try to call dealloc yourself. 
Always call superclass dealloc to make sure that all of 
the instance variables in parent classes are properly 
released.
Automatic Reference Counting 
ARC works exact same way as MRR, but it automatically 
inserts the appropriate memory management methods for 
you. 
Takes the human error out of memory management. 
To enable ARC – Build Settings -> Automatic Reference 
Counting -> Yes 
Not allowed to manually call retain, release or autorelease 
New @property attributes assign -> weak 
retain -> strong
Fully featured version of ARC was delivered by apple 
in 2011 on MAC OS X Lion & ios5 
Before that a limited version of ARC (ARCLite) was 
supported in Xcode4.2 or later, MAC OS X 10.6, ios 
4.0… which does not included weak reference 
support 
In case of ARCLite we can use unsafe_unretained in 
place of weak.
Zeroing weak references 
Difference between ARC & ARCLite is of zeroing weak 
references 
It is a feature in ARC to set weak reference pointers to nil 
when the object it is pointing to is deallocated. 
Prior to this weak not set to nil, leading to dangling 
pointers (unsafe_unretained). The programmer has to 
manually set the reference to nil. 
This needs additional support from objC runtime, hence 
only available after OSXLion or ios5
Garbage Collector 
Starting in MAC OS X 10.5 we got automatic memory 
management on MAC OS X (not in ios) with 
Autozone(libAuto) 
Works at runtime 
Trade a bit of CPU time to let libauto collect objects that are 
out of scope and no longer referenced. 
Libauto is opensource.. 
http://opensource.apple.com/source/libauto/libauto-141.2/ 
Xcode, Rapidweaver etc use garbage collector
Thank You

More Related Content

What's hot

Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]Kuba Břečka
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Nida Ismail Shah
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろうUnity Technologies Japan K.K.
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement SauvageCocoaHeads France
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsIgnacio Martín
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative versionWO Community
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Nida Ismail Shah
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 

What's hot (20)

Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
iOS5 NewStuff
iOS5 NewStuffiOS5 NewStuff
iOS5 NewStuff
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
Data perisistence in iOS
Data perisistence in iOSData perisistence in iOS
Data perisistence in iOS
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 

Viewers also liked

Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotionMichael Denomy
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーSatoshi Asano
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in AndoidMonkop Inc
 
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
 
Memory Management
Memory ManagementMemory Management
Memory ManagementVisakh V
 

Viewers also liked (6)

Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotion
 
Android & IOS
Android & IOSAndroid & IOS
Android & IOS
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
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
 
Memory Management
Memory ManagementMemory Management
Memory Management
 

Similar to Memory management in Objective C

Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newwilliamethan912
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Garbage collection
Garbage collectionGarbage collection
Garbage collectionSomya Bagai
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
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
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
 
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
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightGiuseppe Arici
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Countingpragmamark
 
Constructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptxConstructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptxrevathi s
 

Similar to Memory management in Objective C (20)

Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory new
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
svelte-en.pdf
svelte-en.pdfsvelte-en.pdf
svelte-en.pdf
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Lecture 3-ARC
Lecture 3-ARCLecture 3-ARC
Lecture 3-ARC
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
 
Memory management
Memory managementMemory management
Memory management
 
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
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
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
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Constructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptxConstructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptx
 

Recently uploaded

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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

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...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Memory management in Objective C

  • 1. MEMORY MANAGEMENT IN OBJECTIVE C By: Neha Gupta Software Engineer, Mindfire Solutions, Noida Follow at: http://developersarea.wordpress.com/ https://www.facebook.com/programmingtipstechniques
  • 2. MEMORY MANAGEMENT - Allocation and Recycling When a program requests a block of memory, memory manager assigns that block to program. When the program no longer need that data, those blocks become available for reassignment. This task can be done manually (by the programmer) or automatically (by the memory manager)
  • 3. Memory Management in Objective C ios 4 and below – Manual memory management ios 5 and above – Automatic Reference Counting OS X 10.4 and below – Manual memory management OS X 10.5 – 10.7 – Garbage Collector OS X 10.7 – Automatic Reference Counting
  • 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. Taking ownership of an object alloc - Create an object and claim ownership of it. copy - Copy object and claim ownership of it. retain - Claim ownership of an existing object. You own a object if: SomeClass* obj = [[SomeClass alloc]init]; SomeClass* obj = [SomeClass copy]; SomeClass* obj = [SomeClass new];
  • 6. Relinquishing ownership of an Object release – Relinquishing ownership of an object and destroy it immediately. autorelease – Relinquishing ownership of an object but defer its destruction.
  • 7. When you forget to balance any alloc, retain & copy call with a release or autorelease on same object : If you forget to release an object, its underlying memory is never freed, resulting in memory leak. If you release object too many times, it will result into dangling pointer.
  • 8. The retain method @interface MyClass : NSObject { NSMutableArray* _values; } - (NSMutableArray*)values; - (void)setValues : (NSMutableArray*)newValues; Will create weak reference if implemented as below: - (NSMutableArray*)values { return _values; } - (void)setValues : (NSMutableArray*)newValues { _values = newValues; }
  • 9. Now in main, NSMutableArray* addValues = [[NSMutableArray alloc]init]; [addValues addObject: @”abcd”]; MyClass* class1 = [[MyClass alloc]init]; [class1 setValues: addValues]; [addValues release]; NSLog(@”%@”,[class1 values]); //error, dangling pointer Because the objet is already released, class1 object has weak reference to array.
  • 10. Correct way…. MyClass needs to claim ownership of the array as : - (void)setValues : (NSMutableArray*)newValues { _values = [newValues retain] ; //refcount = 2 } This ensures the object wont be released while our class object is using it. But this code creates another problem…
  • 11. The retain call isn’t balanced with a release, so we have another memory leak. Here as soon as we pass another value to setValues: , we cant access the old value, which means we can never free it. To fix this setValues: needs to call release on the old value - (void)setValues : (NSMutableArray*)newValues { if(_values == newValues) { return; } NSMutableArray* oldval = _values; _values = [newValues retain] ; //refcount = 2 [oldval release]; } This is basically what “strong” and “retain” property attributes do.
  • 12. The copy method.. - Creates a brand new instance of the object and increments the reference count on that leaving the original unaffected.
  • 13. Autorelease method - Relinquishes ownership of an object - Doesn’t destroy the object immediately - Defer the freeing of memory until later on in the program Ex:- +(MyClass*) classObj{ MyClass* obj = [[MyClass alloc]init]; return [obj autorelease]; } Methods like stringWithFormat: and stringWithString: works the same way… It waits until the nearest @autoreleasepool{} block after which it calls a normal release method on all autorelease objects.
  • 14. AutoRelease Pools Maintains a list of objects that will be sent release messages when those pools are destroyed. Can be nested You should always create a autorelease pool whenever you create a new thread.
  • 15. The dealloc method Called right before the object is destroyed, giving you a chance to clean up any internal objects. Called automatically by runtime. You should never try to call dealloc yourself. Always call superclass dealloc to make sure that all of the instance variables in parent classes are properly released.
  • 16. Automatic Reference Counting ARC works exact same way as MRR, but it automatically inserts the appropriate memory management methods for you. Takes the human error out of memory management. To enable ARC – Build Settings -> Automatic Reference Counting -> Yes Not allowed to manually call retain, release or autorelease New @property attributes assign -> weak retain -> strong
  • 17. Fully featured version of ARC was delivered by apple in 2011 on MAC OS X Lion & ios5 Before that a limited version of ARC (ARCLite) was supported in Xcode4.2 or later, MAC OS X 10.6, ios 4.0… which does not included weak reference support In case of ARCLite we can use unsafe_unretained in place of weak.
  • 18. Zeroing weak references Difference between ARC & ARCLite is of zeroing weak references It is a feature in ARC to set weak reference pointers to nil when the object it is pointing to is deallocated. Prior to this weak not set to nil, leading to dangling pointers (unsafe_unretained). The programmer has to manually set the reference to nil. This needs additional support from objC runtime, hence only available after OSXLion or ios5
  • 19. Garbage Collector Starting in MAC OS X 10.5 we got automatic memory management on MAC OS X (not in ios) with Autozone(libAuto) Works at runtime Trade a bit of CPU time to let libauto collect objects that are out of scope and no longer referenced. Libauto is opensource.. http://opensource.apple.com/source/libauto/libauto-141.2/ Xcode, Rapidweaver etc use garbage collector