Objective-C Memory Management [memo]

[1].Memory management Manually

all objective-C classes subclass NSObject
1.NSObject classes are reference counted
2.When reference count == 0 , memory released

init or copy :reference count=1
release: reference count —
retain: reference count++

convention: methods beginning with anything but init or copy:
return “autoreleased objects”

autorelease: reference count — (later on)

1.Properties can be marked to retain

clean up in super dealloc


add Swater object

now turn off the ARC

MemoryTest/Build Settings/ search automatic Ref / Switch to NO

New File / cocoa Touch class /set class name to Sweater and subclass of NSObject

create Sweater.h
create Sweater.m
create Person.h
create Person.m
add in AppDelegate.m
add Sweater object
graySweater and blueSweater RefCount minus 1
GraySweater RefCount add 1
after ray.swater = nil
after Ray release and vicki release
no object reference to GraySweater, so GraySwater RefCount=0 to release
finally app have

check memory leaks in xcode

chosen Leaks
Press Red Button to start check memory leaks
we don’t found our Person or Sweater object , good!
now annotation these code to let it leaks
you found one Sweater object and two Person object have memory leaks!


[2].Memory management With ARC
1.when turn on ARC , you can’t use retain , release , autorelease, dealloc
2.ARC != garbage collection
3.declare pointer variables as __strong(default) and __weak

turn on ARC

memoryTest/BuildSettings/Search automatic Ref / switch to YES
annotation dealloc
replace retain with strong
remove all retain , autorelease , release
program result

use ARC’s potential problem : retain cycle

Due to two variable all are strong property, each object must waiting for other object release. these two object never release forever!
change Vicki to __weak , vicki refCount will be zero , so vicki release first
now Gray also release

Add code to Demo retain cycle

only release two object
check memory leaks
now replace strong to weak to prevent retain cycle
now no retain cycle in graph.
no any leaks


Data From

Edit history:
20171123 add

For the last few years. i was involved mostly in the development of Automatic Fare collection system for the Chennai Metro. Familiar with C++ and iOS.