我在主线程中这样做:
CCAnimation *anim; //class variable
[NSThread detachNewThreadSelector:@selector(loadAimation) toTarget:self withObject:nil];
在loadAimation中:
-(void) loadAnimation {
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
anim = [[CCAnimaton alloc] init];
[autoreleasepool drain];
}
在主线程中我发布它:
[anim release];
现在我想问一下内存管理是否合适。
答案 0 :(得分: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];
}
答案 1 :(得分:0)
当然,如果您要保护对指针变量的访问,那应该没问题。