我正在尝试从一个网址加载一个图像在背景中。如果我所传递的都是NSUrl,那么代码就会工作得很好。如果我试图传递一个带有额外变量的NSArray,它永远不会被调用:
这段代码运行得很好,LoadImage2被调用,而后者又很好地调用了ImageLoaded2。
- (void)LoadBackgroundImage2: (char*)pImageURL
{
NSString* pImageURLString = [NSString stringWithFormat:@"%s", pImageURL];
NSLog( @"LoadBackgroundImage2: %@", pImageURLString );
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(LoadImage2:)
object:pImageURLString];
[queue addOperation:operation];
[operation release];
}
- (void)LoadImage2: (NSString*)pImageURL
{
NSLog( @"LoadImage2: %@", pImageURL );
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:pImageURL]];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
[imageData release];
[self performSelectorOnMainThread:@selector(ImageLoaded2:) withObject:image waitUntilDone:NO];
}此代码不起作用。LoadImage从不被调用:
- (void)LoadBackgroundImage: (char*)pImageURL :(int)textureID :(int)textureType
{
printf( "LoadBackgroundImage( %s, %d, %d)\n", pImageURL, textureID, textureType );
NSString* pImageURLString = [NSString stringWithFormat:@"%s", pImageURL];
NSArray* pUrlAndReferences = [[[NSArray alloc] initWithObjects: pImageURLString, textureID, textureType, nil] autorelease];
NSOperationQueue *queue = [[NSOperationQueue new] autorelease];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(LoadImage:)
object:pUrlAndReferences];
[queue addOperation:operation];
[operation release];
}
- (void)LoadImage: (NSArray*)pUrlAndReferences
{
NSString* pImageUrl = [pUrlAndReferences objectAtIndex: 0];
int textureId = [ [ pUrlAndReferences objectAtIndex: 1 ] intValue ];
int textureType = [ [ pUrlAndReferences objectAtIndex: 2 ] intValue ];
NSLog( @"\n\nLoadImage: %@, %d, %d\n", pImageUrl, textureId, textureType );
NSData* pImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:pImageUrl]];
UIImage* pImage = [[[UIImage alloc] initWithData:pImageData] autorelease];
NSArray* pImageAndReferences = [[[NSArray alloc] initWithObjects: pImage, textureId, textureType, nil] autorelease];
[pImageData release];
[self performSelectorOnMainThread:@selector(ImageLoaded:) withObject:pImageAndReferences waitUntilDone:NO];
}有人知道为什么LoadImage没有被呼叫吗?
谢谢。
发布于 2012-11-01 20:05:36
我的猜测是你没有保留你的队列。下面是正在发生的事情
NSInvocationOperation,它被保留(没问题)NSInvocationOperation进入队列(保留),然后被释放。这里没有问题,因为保留计数仍然是1:1 (alloc) +1 (retain) -1 (release) =1= not dealloced.new = alloc+init),然后自动释放,但它不会被保留在其他地方。问题来了:因为您已经自动释放了队列,一旦方法LoadBackgroundImage完成,队列的保留计数就会为0,并且它会自动释放,因此,您的调用将不会被执行。如果这就是问题所在,您可以尝试从队列中删除autorelease调用。如果我是正确的,你的代码应该可以工作。但请注意,这不是一个好的解决方案,因为您正在丢失内存。这只是为了看看它是否有效。
你绝对应该创建一个类,一个单例,一个实例变量或任何你喜欢的东西来保留队列的实例。此外,最好为所有LoadBackgroundImage调用只有一个队列,而不是每次都创建一个新队列。
https://stackoverflow.com/questions/12504965
复制相似问题