Asymptote
Asymptote

Reputation: 1150

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

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.

Upvotes: 1

Views: 1067

Answers (2)

outis
outis

Reputation: 77440

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];
}

Upvotes: 1

Elalfer
Elalfer

Reputation: 5338

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

Upvotes: 0

Related Questions