Objective-C:在一个线程中分配,在另一个线程中释放 [英] Objective-C: Allocation in one thread and release in other

查看:105
本文介绍了Objective-C:在一个线程中分配,在另一个线程中释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在主线程中这样做:

I am doing this in my Main Thread:

CCAnimation *anim; //class variable

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

在loadAimation中:

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.

推荐答案

可以在一个线程中分配对象,然后在另一个线程中取消分配对象.但是,根据您的处理方式,您的代码可能会错误地执行此操作.

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.

如果可能,将anim变成一个属性,这样就不必担心内存管理.如果不能,则可以应用访问器模式,但必须自己实现.

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

这篇关于Objective-C:在一个线程中分配,在另一个线程中释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆