1

我在我的主线程中这样做:

CCAnimation *anim; //class variable

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

在加载动画中:

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

在主线程中我释放它:

        [anim release];

现在我想问一下关于内存管理是否可以。

4

2 回答 2

1

可以在一个线程中分配对象并在另一个线程中释放它。但是,根据您的处理方式,您的代码可能会错误地执行此操作。

如果可能的话,anim变成一个属性,这样你就不必太担心内存管理了。如果不能,您可以应用访问器模式,但您必须自己实现它。

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];
}
于 2011-01-15T06:05:07.403 回答
0

当然,如果您要保护对指针变量的访问,那应该没问题。

于 2011-01-15T05:54:25.687 回答