简体   繁体   中英

Assign or retain in cocos2d and objective C

Here's my current situation: I have a NSMutableArray named dictKeyArray which I assign a property with @property(nonatomic,retain)NSMutableArray *dictKeyArray
I synthesize my mutable array in the implementation file.
Later, I have a dictionary name storeDict. I assign all the keys of the dictionary to the dictKeyArray like so:
dictKeyArray = [[storeDict allKeys] mutableCopy];
Now I use this dictionary later in my implementation file. However, when it comes to releasing it, I release it once in my dealloc method. When checking with instruments, a leak shows up! Why is dictKeyArray leaking? Should I be using assign instead of retain ? I'm still not clear on what the difference is exactly... thank you!

You have to send it an

[[[storeDict allKeys] mutableCopy] autorelease];

Just to make this clear: mutableCopy does the same as alloc meaning you are claiming ownership of the object in question. You have to decrease the retainCount by one.

By the way: You should use the accessor you wrote for it. You are just assigning it to your iVar at the moment. If you want to make your accessors work, you will have to use something like

object.dictKeyArray = ...;

in general. Or here (as mentioned by dreamlax)

self.dictKeyArray = ...;

because you are referring to an object of this specific class the code is in.

Only this way you are ensuring your object is properly retained by your accessor. Otherwise writing the accessor code doesn't make sense at all because it never gets called.

Please note: As Josh said in the comments, your code should be valid (at least from my point of view). What I suggested is a solution that is not as error-prone as yours because you adhere to the rules (could save you from headache in the near future).

You should be using self.dictKeyArray = ... . Without the self. you are accessing the instance variable directly, bypassing any memory management benefits of properties, but, remember that you own the result of mutableCopy , and assigning to a property that also takes ownership will result in double-ownership, so use:

self.dictKeyArray = [[[storeDict allKeys] mutableCopy] autorelease];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM