Difference between revisions of "Reference counting"

From GNUstepWiki
Jump to navigation Jump to search
m
 
m
 
Line 5: Line 5:
  
 
===Example===
 
===Example===
<code>
+
<source lang="objc">
  
 
-(void)myMethod:(NSObject*)myObject
 
-(void)myMethod:(NSObject*)myObject
Line 15: Line 15:
  
 
}
 
}
</code>
+
</source>
 
===Tight Loop===
 
===Tight Loop===
 
<code>
 
<code>

Latest revision as of 20:21, 21 July 2012

Reference counting is used to automatically deallocate objects when they are no longer needed.

Using reference counting

By convention when using an autorelased object you must "retain" before using it, and release it when you are done with it. For consistency you may "retain the object you want at the beginign of your method, and release it at the end, though in a tight loop you may wish to only retain once.

Example

<source lang="objc">

-(void)myMethod:(NSObject*)myObject {

[myObject retain] //my code [myObject release]

} </source>

Tight Loop

-(void)myMethod:(NSObject*)myObject {

[myObject retain] for(int64_t i = 0; i<LONG_LONG_MAX; i++)

{

[self mySubMethod:myObject]

}

[myObject release]

}

-(void)mySubMethod:(NSObject*)myObject {

//Remove retain/relase overhead

//[myObject* retain]

//my code

//[myObject* release]

}


See also

Wikipedia on reference counting