Initializing several ivars of the same type with same object?
So, this is pretty standard memory management, from what I understand:
ClassName *temp=[[ClassName alloc] init];
self.ivar=temp;
[temp release];
This is to avoid the memory leak created by just doing this:
self.ivar=[[ClassName alloc] init];
Cool. But, suppose I have several ivars that are based ClassName
? Is this okay:
ClassName *temp=[[ClassName all开发者_运维技巧oc] init];
self.ivar=temp;
self.othervar=temp;
self.anothervar=temp;
[temp release];
Would they all be manipulating the same object, ultimately, even though I want them to have different instances of ClassName
? I assume that the outcome of this might depend on if the ivars were created as retain
vs copy
? Suppose they are set to retain
, would this be okay?
Would they all be manipulating the same object, ultimately, even though I want them to have different instances of ClassName?
the default expectation is "yes, they would reference the same object because this is a reference counted system."
I assume that the outcome of this might depend on if the ivars were created as retain vs copy?
not might, but entirely. if the property is declared copy
and the type adopts NSCopying
, that should be all that is needed. if you implement the setters (what are often synthesized properties) yourself, you must copy
in your implementations.
Suppose they are set to retain, would this be okay?
then they would all refer to the same instance. whether that is the correct semantic for your program depends on how you need it to behave. in this example, you stated "I want them to have different instances of ClassName" so you would either need to create an unique instance for every destination (either directly or via copy
, if ClassName
adopts NSCopying
).
If the properties are all retain
then you will be storing the same instance three times, as you assume. If you want different instances, and you want to use retain
, then you need to create three different instances. copy
will create a copy, but then it will do this every time you set anything to the property, which may not be your desired behaviour.
In your example all objects will point/manipulate same object instance unless they are
copy/mutableCopy
or any other type that conforms to NSCopying protocol.
retain will have no affect other than incrementing retainCount of an already allocated object.
精彩评论