Hello,
I am creating a bunch of Sprites using initwithCGImage, using images that i am downloading from a server. This works fine most of the time, but sometimes even though it will download the correct image, it will display a previously downloaded image, this seems to happen at random. I am using cocos 0.8.2. I think this is related to issue #349?. Does anyone have a workaround for this? the issue is still open.
Additionally before each sprite creation, I am removing my sprite using [self removechild:mySprite], therefore as I understand this shouldn't happen at all, since I am only displaying one Sprite at a time, yet sometimes when I download the new image and use the initwithCGImage the Sprite points to a previously downloaded CGImage.
Here is some of my code:
- (void) startDownload {
self.activeDownload = [NSMutableData data];
NSString *imageURL=[self.pList objectForKey:[NSString stringWithFormat:@"%d", next]];
// alloc+init and start an NSURLConnection; release on completion/failure
NSLog(@"Downloading from url %@", imageURL);
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:imageURL]] delegate:self];
self.imageConnection = conn;
[conn release];
}
#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.activeDownload appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR DOWNLOADING");
// Clear the activeDownload property to allow later attempts
self.activeDownload = nil;
// Release the connection now that it's finished
self.imageConnection = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"FINISH DOWNLOAD");
// Set Image and clear temporary data/image
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
self.activeDownload = nil;
if (next != [self.myArray count])
{
next++;
}
else
{
next= 1;
}
Sprite = [Sprite spriteWithCGImage:image.CGImage];
Sprite.shearX = -.11;
Sprite.shearY = .097;
[Sprite setPosition:ccp(235 , 48)];
[self addChild:Sprite z:kTag tag:2];
//Add new Sprite to chipmunks space
[self addSpriteToSpace];
// Release the connection now that it's finished
self.imageConnection = nil;
//Release Image
[image release];
}
The start download is called after the removeChild happens after, which happens every so often.
UPDATE: This is indeed the issue because
-(Texture2D*) addCGImage: (CGImageRef) image forKey: (NSString *)key
{
NSAssert(image != nil, @"TextureMgr: image MUST not be nill");
Texture2D * tex;
if( (tex=[textures objectForKey: key] ) ) {
return tex;
}
tex = [[Texture2D alloc] initWithImage: [UIImage imageWithCGImage:image]];
[textures setObject: tex forKey:key];
return [tex autorelease];
}
commenting the if, gets rid of this, although I know this is not a good solution.
Thank you.
-Oscar