开发者

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

开发者 https://www.devze.com 2023-02-04 03:38 出处:网络
I am doing this in my Main Thread: CCAnimation *anim; //class variable [NSThread detachNewThreadSelector:@selector(loadAimation) toTarget:self withObject:nil];

I am doing this in my Main Thread:

CCAnimation *anim; //class variable

[NSThread detachNewThreadSelector:@selector(loadAimation) toTarget:self withObject:nil];

In loadAimation:

-(vo开发者_运维百科id) 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消