- (void)viewDidLoad
{
[super viewDidLoad];
[self getImages];
}
-(void)getImages
{
receivedData = [[NSMutableData alloc]init];
myImages = [[NSMutableArray alloc]init];
myImagesAdresses = [[NSMutableArray alloc]initWithCapacity:5];
[myImagesAdresses addObject:@"adress/Images/3.png"];
[myImagesAdresses addObject:@"adress/Images/2.png"];
[myImagesAdresses addObject:@"adress/Images/1.png"];
[myImagesAdresses addObject:@"adress/Images/0.png"];
[self loadNextImage];
}
-(void)loadNextImage
{
if([myImagesAdresses count])
{
NSURL * imageURL = [NSURL URLWithString:[myImagesAdresses lastObject]];
NSURLRequest * myRequest = [NSURLRequest requestWithURL:imageURL];
[[NSURLConnection alloc]initWithRequest:myRequest delegate:self];
NSLog(@"Start load URL %@",imageURL);
}
else {
[self.theImage setImage:[myImages objectAtIndex:2]];
[self changeImage];
NSLog(@"No More Images to Load");
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[connection release];
connection = nil;
NSLog(@"Image from %@ loaded",[myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
connection =nil;
NSLog(@"Image from %@ not loaded", [myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
和更改图片的代码:
-(void)changeImage
{
SEL selectorToCall = @selector(change: );
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selectorToCall];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:self];
[invocation setSelector:selectorToCall];
NSTimer * newTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:YES];
self.paintingTimer = newTimer;
}
- (void) change:(NSTimer *)paramTimer
{
static NSInteger currentElement = 0;
if(++currentElement == [myImages count]) currentElement = 0;
[self.theImage setImage:[myImages objectAtIndex:currentElement]];
}
- (void) stopPainting
{
if (self.paintingTimer != nil){
[self.paintingTimer invalidate];
}
}
我没有收到任何错误,但图片根本就没有改变......
答案 0 :(得分:1)
看起来receivedData
是一个你反复追加的ivar,但它永远不会被清除。因此,在收到第一张图像后,第二张图像会附加到其上,等等。
在此行之后,您应该清空receivedData
:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
答案 1 :(得分:1)
您应该在以下代码后添加以下代码:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
像这样:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[receivedData setData:nil];