Objective-C: distribution in one thread and release in another

I do this in the main topic:

CCAnimation *anim; //class variable [NSThread detachNewThreadSelector:@selector(loadAimation) toTarget:self withObject:nil]; 

In loadAimation:

 -(void) loadAnimation { NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; anim = [[CCAnimaton alloc] init]; [autoreleasepool drain]; } 

And in the main thread, I release it:

  [anim release]; 

Now I want to ask if this is good with regard to memory management.

+1
source share
2 answers

You can select an object in one thread and release it in another. However, depending on how you approach it, your code may do it wrong.

Turn anim into a property if possible, so you don’t have to worry about memory management that much. If you cannot, you can apply the access pattern, but you must implement it yourself.

 static CCAnimation *anim=nil; +(CCAnimation*)anim { @synchronized(self) { return [[anim retain] autorelease]; } } +(void)setAnim:(CCAnimation*)animation { @synchronized(self) { if (anim != animation) { [anim release]; anim = [animation retain]; } } } -(void)loadAnimation { NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; [[self class] setAnim:[[[CCAnimaton alloc] init] autorelease]]; [autoreleasepool drain]; } 
+1
source

This should be fine, of course, if you are protecting access to a pointer variable.

0
source

Source: https://habr.com/ru/post/1341947/


All Articles