Objective-C: Allocation in one thread and release

2019-07-22 06:00发布

问题:

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.