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

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
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
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
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
 
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
 
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.
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
(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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
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...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
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...
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
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
 
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
 
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...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
(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...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 

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