Memory Management Policy
2014-09-01 20:39
351 查看
NSObject
astandardmethodnamingconvention.The
NSObjectclassalsodefinesamethod,
dealloc,
thatisinvokedautomaticallywhenanobjectisdeallocated.ThisarticledescribesallthebasicrulesyouneedtoknowtomanagememorycorrectlyinaCocoaprogram,andprovidessomeexamplesofcorrectusage.
BasicMemoryManagementRules
Thememorymanagementmodelisbasedonobjectownership.Anyobjectmayhaveoneormoreowners.Aslongasanobjecthasatleastoneowner,itcontinuestoexist.Ifanobjecthasnoowners,theruntimesystemdestroysitautomatically.Tomakesureitisclearwhenyouownanobjectandwhenyoudonot,Cocoasetsthefollowingpolicy:
Youownanyobjectyoucreate
Youcreateanobjectusingamethodwhosenamebeginswith“alloc”,“new”,“copy”,or“mutableCopy”(forexample,
,alloc
,newObject
or
).mutableCopy
Youcantakeownershipofanobjectusingretain
Areceivedobjectisnormallyguaranteedtoremainvalidwithinthemethoditwasreceivedin,andthatmethodmayalsosafelyreturntheobjecttoitsinvoker.Youuse
retainin
twosituations:(1)Intheimplementationofanaccessormethodoran
initmethod,totakeownershipofanobjectyouwanttostoreasapropertyvalue;and(2)Toprevent
anobjectfrombeinginvalidatedasaside-effectofsomeotheroperation(asexplainedin“Avoid
CausingDeallocationofObjectsYou’reUsing”).
Whenyounolongerneedit,youmustrelinquishownershipofanobjectyouown
Yourelinquishownershipofanobjectbysendingita
messagerelease
oran
message.autorelease
InCocoaterminology,relinquishingownershipofanobjectisthereforetypicallyreferredtoas“releasing”anobject.
Youmustnotrelinquishownershipofanobjectyoudonotown
Thisisjustcorollaryofthepreviouspolicyrules,statedexplicitly.
ASimpleExample
Toillustratethepolicy,considerthefollowingcodefragment:{ |
Person*aPerson=[[Personalloc]init]; |
//... |
NSString*name=aPerson.fullName; |
//... |
[aPersonrelease]; |
} |
allocmethod,soitissubsequentlysenta
releasemessage
whenitisnolongerneeded.Theperson’snameisnotretrievedusinganyoftheowningmethods,soitisnotsenta
releasemessage.Notice,though,thattheexampleuses
releaserather
than
autorelease.
UseautoreleasetoSendaDeferredrelease
Youuseautoreleasewhenyouneedtosendadeferred
releasemessage—typically
whenreturninganobjectfromamethod.Forexample,youcouldimplementthe
fullNamemethodlikethis:
-(NSString*)fullName{ |
NSString*string=[[[NSStringalloc]initWithFormat:@"%@%@", |
self.firstName,self.lastName]autorelease]; |
returnstring; |
} |
alloc.Toabidebythememorymanagementrules,youmustrelinquishownershipofthestringbefore
youlosethereferencetoit.Ifyouuse
release,however,thestringwillbedeallocatedbeforeitisreturned(andthemethodwouldreturnaninvalidobject).Using
autorelease,
yousignifythatyouwanttorelinquishownership,butyouallowthecallerofthemethodtousethereturnedstringbeforeitisdeallocated.
Youcouldalsoimplementthe
fullNamemethodlikethis:
-(NSString*)fullName{ |
NSString*string=[NSStringstringWithFormat:@"%@%@", |
self.firstName,self.lastName]; |
returnstring; |
} |
stringWithFormat:,soyoucansafelyreturnthestringfrom
themethod.
Bywayofcontrast,thefollowingimplementationiswrong:
-(NSString*)fullName{ |
NSString*string=[[NSStringalloc]initWithFormat:@"%@%@", |
self.firstName,self.lastName]; |
returnstring; |
} |
fullNamemethodownsthereturnedstring.
Thecallerthereforehasnoreasontoreleasethereturnedstring,anditwillthusbeleaked.
YouDon’tOwnObjectsReturnedbyReference
SomemethodsinCocoaspecifythatanobjectisreturnedbyreference(thatis,theytakeanargumentoftypeClassName**or
id*).
Acommonpatternistousean
NSErrorobjectthatcontainsinformationaboutanerrorifoneoccurs,asillustratedby
(initWithContentsOfURL:options:error:
NSData)
and
(initWithContentsOfFile:encoding:error:
NSString).
Inthesecases,thesamerulesapplyashavealreadybeendescribed.Whenyouinvokeanyofthesemethods,youdonotcreatethe
NSErrorobject,
soyoudonotownit.Thereisthereforenoneedtoreleaseit,asillustratedinthisexample:
NSString*fileName=<#Getafilename#>; |
NSError*error; |
NSString*string=[[NSStringalloc]initWithContentsOfFile:fileName |
encoding:NSUTF8StringEncodingerror:&error]; |
if(string==nil){ |
//Dealwitherror... |
} |
//... |
[stringrelease]; |
ImplementdealloctoRelinquishOwnershipofObjects
TheNSObjectclassdefinesamethod,
,dealloc
thatisinvokedautomaticallywhenanobjecthasnoownersanditsmemoryisreclaimed—inCocoaterminologyitis“freed”or“deallocated.”.Theroleofthe
deallocmethod
istofreetheobject'sownmemory,andtodisposeofanyresourcesitholds,includingownershipofanyobjectinstancevariables.
Thefollowingexampleillustrateshowyoumightimplementa
deallocmethodforaPersonclass:
@interfacePerson:NSObject |
@property(retain)NSString*firstName; |
@property(retain)NSString*lastName; |
@property(assign,readonly)NSString*fullName; |
@end |
@implementationPerson |
//... |
-(void)dealloc |
[_firstNamerelease]; |
[_lastNamerelease]; |
[superdealloc]; |
} |
@end |
deallocmethoddirectly.
Youmustinvokethesuperclass’simplementationattheendofyourimplementation.
Youshouldnottiemanagementofsystemresourcestoobjectlifetimes;see“Don’t
UsedealloctoManageScarceResources.”
Whenanapplicationterminates,objectsmaynotbesenta
deallocmessage.Becausetheprocess’smemoryisautomaticallycleared
onexit,itismoreefficientsimplytoallowtheoperatingsystemtocleanupresourcesthantoinvokeallthememorymanagementmethods.
CoreFoundationUsesSimilarbutDifferentRules
TherearesimilarmemorymanagementrulesforCoreFoundationobjects(seeMemoryManagementProgrammingGuideforCoreFoundation).ThenamingconventionsforCocoaandCoreFoundation,however,aredifferent.Inparticular,CoreFoundation’sCreateRule(see“The
CreateRule”inMemory
ManagementProgrammingGuideforCoreFoundation)doesnotapplytomethodsthatreturnObjective-Cobjects.Forexample,inthefollowingcodefragment,youarenotresponsibleforrelinquishingownershipof
myInstance:
相关文章推荐
- Memory Management Policy(内存管理政策)
- IOS内存管理策略(Memory Management Policy)
- Memory Management Policy
- IOS内存管理策略(Memory Management Policy)
- 内存管理策略(memory Management Policy)
- memblock -- a simple memory management module
- Objective-C Memory Management For Lazy People
- Windows 2000 Page Based Memory Management
- Garbage Collection: Algorithms for Automatic Dynamic Memory Management
- Advanced Memory Management: Dynamic Allocation, Part 1
- Memory Management for Android Apps 笔记之 GC
- Memory Management in Cocoa Program
- Very simple rules for memory management in Cocoa
- JSBinding + SharpKit / Memory Management (GC)
- How JavaScript works: memory management + how to handle 4 common memory leaks
- Java Memory Management Skill List
- Memory Management in Open Cascade
- Objective-C Memory Management
- [转]Creating a custom information management policy
- Memory Management of Instance Variables (ARC)