您的位置:首页 > 其它

Memory Management Policy

2014-09-01 20:39 351 查看



Thebasicmodelusedformemorymanagementinareference-countedenvironmentisprovidedbyacombinationofmethodsdefinedinthe
NSObject
protocoland
astandardmethodnamingconvention.The
NSObject
classalsodefinesamethod,
dealloc
,
thatisinvokedautomaticallywhenanobjectisdeallocated.ThisarticledescribesallthebasicrulesyouneedtoknowtomanagememorycorrectlyinaCocoaprogram,andprovidessomeexamplesofcorrectusage.


BasicMemoryManagementRules

Thememorymanagementmodelisbasedonobjectownership.Anyobjectmayhaveoneormoreowners.Aslongasanobjecthasatleastoneowner,itcontinuestoexist.Ifanobjecthasnoowners,theruntimesystem
destroysitautomatically.Tomakesureitisclearwhenyouownanobjectandwhenyoudonot,Cocoasetsthefollowingpolicy:

Youownanyobjectyoucreate
Youcreateanobjectusingamethodwhosenamebeginswith“alloc”,“new”,“copy”,or“mutableCopy”(forexample,
alloc
,
newObject
,
or
mutableCopy
).

Youcantakeownershipofanobjectusingretain
Areceivedobjectisnormallyguaranteedtoremainvalidwithinthemethoditwasreceivedin,andthatmethodmayalsosafelyreturntheobjecttoitsinvoker.Youuse
retain
in
twosituations:(1)Intheimplementationofanaccessormethodoran
init
method,totakeownershipofanobjectyouwanttostoreasapropertyvalue;and(2)Toprevent
anobjectfrombeinginvalidatedasaside-effectofsomeotheroperation(asexplainedin“Avoid
CausingDeallocationofObjectsYou’reUsing”).

Whenyounolongerneedit,youmustrelinquishownershipofanobjectyouown
Yourelinquishownershipofanobjectbysendingita
release
message
oran
autorelease
message.
InCocoaterminology,relinquishingownershipofanobjectisthereforetypicallyreferredtoas“releasing”anobject.

Youmustnotrelinquishownershipofanobjectyoudonotown
Thisisjustcorollaryofthepreviouspolicyrules,statedexplicitly.


ASimpleExample

Toillustratethepolicy,considerthefollowingcodefragment:

{

Person*aPerson=[[Personalloc]init];

//...

NSString*name=aPerson.fullName;

//...

[aPersonrelease];

}

ThePersonobjectiscreatedusingthe
alloc
method,soitissubsequentlysenta
release
message
whenitisnolongerneeded.Theperson’snameisnotretrievedusinganyoftheowningmethods,soitisnotsenta
release
message.Notice,though,thattheexampleuses
release
rather
than
autorelease
.


UseautoreleasetoSendaDeferredrelease

Youuse
autorelease
whenyouneedtosendadeferred
release
message—typically
whenreturninganobjectfromamethod.Forexample,youcouldimplementthe
fullName
methodlikethis:

-(NSString*)fullName{

NSString*string=[[[NSStringalloc]initWithFormat:@"%@%@",

self.firstName,self.lastName]autorelease];

returnstring;

}

Youownthestringreturnedby
alloc
.Toabidebythememorymanagementrules,youmustrelinquishownershipofthestringbefore
youlosethereferencetoit.Ifyouuse
release
,however,thestringwillbedeallocatedbeforeitisreturned(andthemethodwouldreturnaninvalidobject).Using
autorelease
,
yousignifythatyouwanttorelinquishownership,butyouallowthecallerofthemethodtousethereturnedstringbeforeitisdeallocated.
Youcouldalsoimplementthe
fullName
methodlikethis:

-(NSString*)fullName{

NSString*string=[NSStringstringWithFormat:@"%@%@",

self.firstName,self.lastName];

returnstring;

}

Followingthebasicrules,youdon’townthestringreturnedby
stringWithFormat:
,soyoucansafelyreturnthestringfrom
themethod.
Bywayofcontrast,thefollowingimplementationiswrong:

-(NSString*)fullName{

NSString*string=[[NSStringalloc]initWithFormat:@"%@%@",

self.firstName,self.lastName];

returnstring;

}

Accordingtothenamingconvention,thereisnothingtodenotethatthecallerofthe
fullName
methodownsthereturnedstring.
Thecallerthereforehasnoreasontoreleasethereturnedstring,anditwillthusbeleaked.


YouDon’tOwnObjectsReturnedbyReference

SomemethodsinCocoaspecifythatanobjectisreturnedbyreference(thatis,theytakeanargumentoftype
ClassName**
or
id*
).
Acommonpatternistousean
NSError
objectthatcontainsinformationaboutanerrorifoneoccurs,asillustratedby
initWithContentsOfURL:options:error:
(
NSData
)
and
initWithContentsOfFile:encoding:error:
(
NSString
).
Inthesecases,thesamerulesapplyashavealreadybeendescribed.Whenyouinvokeanyofthesemethods,youdonotcreatethe
NSError
object,
soyoudonotownit.Thereisthereforenoneedtoreleaseit,asillustratedinthisexample:

NSString*fileName=<#Getafilename#>;

NSError*error;

NSString*string=[[NSStringalloc]initWithContentsOfFile:fileName

encoding:NSUTF8StringEncodingerror:&error];

if(string==nil){

//Dealwitherror...

}

//...

[stringrelease];


ImplementdealloctoRelinquishOwnershipofObjects

The
NSObject
classdefinesamethod,
dealloc
,
thatisinvokedautomaticallywhenanobjecthasnoownersanditsmemoryisreclaimed—inCocoaterminologyitis“freed”or“deallocated.”.Theroleofthe
dealloc
method
istofreetheobject'sownmemory,andtodisposeofanyresourcesitholds,includingownershipofanyobjectinstancevariables.
Thefollowingexampleillustrateshowyoumightimplementa
dealloc
methodforaPersonclass:

@interfacePerson:NSObject

@property(retain)NSString*firstName;

@property(retain)NSString*lastName;

@property(assign,readonly)NSString*fullName;

@end


@implementationPerson

//...

-(void)dealloc

[_firstNamerelease];

[_lastNamerelease];

[superdealloc];

}

@end

Important:Neverinvokeanotherobject’s
dealloc
methoddirectly.
Youmustinvokethesuperclass’simplementationattheendofyourimplementation.
Youshouldnottiemanagementofsystemresourcestoobjectlifetimes;see“Don’t
UsedealloctoManageScarceResources.”
Whenanapplicationterminates,objectsmaynotbesenta
dealloc
message.Becausetheprocess’smemoryisautomaticallycleared
onexit,itismoreefficientsimplytoallowtheoperatingsystemtocleanupresourcesthantoinvokeallthememorymanagementmethods.


CoreFoundationUsesSimilarbutDifferentRules

TherearesimilarmemorymanagementrulesforCoreFoundationobjects(seeMemory
ManagementProgrammingGuideforCoreFoundation).ThenamingconventionsforCocoaandCoreFoundation,however,aredifferent.Inparticular,CoreFoundation’sCreateRule(see“The
CreateRule”inMemory
ManagementProgrammingGuideforCoreFoundation)doesnotapplytomethodsthatreturnObjective-Cobjects.Forexample,inthefollowingcodefragment,youarenotresponsibleforrelinquishingownershipof
myInstance
:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: