Objective-C: Allocation in one thread and release in other

拥有回忆 提交于 2019-12-24 09:09:51

问题


I am doing this in my Main Thread:

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 main thread I release it:

        [anim release];

Now I want to ask if this is fine regarding memory management.


回答1:


It's possible to allocate an object in one thread and deallocate it in another. However, depending on how you approach it, your code could do it incorrectly.

If possible, turn anim into a property so you don't have to worry so much about memory management. If you can't, you can apply the accessor pattern, but you have to 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];
}



回答2:


It should be ok, of course if you are protecting access to the pointer variable.



来源:https://stackoverflow.com/questions/4698239/objective-c-allocation-in-one-thread-and-release-in-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!