我的头文件中的以下代码有什么问题我有一个属性:
@property (nonatomic,retain) NSMutableArray *imgArray;
当我在最后查看NSLog
时," imgArray"总是空的。我试图在UIImageView
子类中拉出多个图像来制作动画" gif"。问题是数组总是空的,所以它不添加任何图像,因为数组是空的。
在我的.m
文件中:
@implementation AnimatedOverlay
BOOL isValid;
@synthesize imgArray;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self startAnimatingWithFrame:frame];
}
return self;
}
-(void) startAnimatingWithFrame:(CGRect)frame
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDate *today = [NSDate date];
NSDate *hourAgo = [[NSDate alloc] initWithTimeInterval:-3600 sinceDate:today];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat setDateFormat:@"HH"];
NSString *hourString = [dateFormat stringFromDate:today];
[dateFormat setDateFormat:@"HH"];
NSString *hourString2 = [dateFormat stringFromDate:hourAgo];
imgArray = [[NSMutableArray alloc] init];
for(int i=0;i<=5;i++){
NSURL *fileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://radar.weather.gov/ridge/Conus/RadarImg/southeast_%@_%@%i8_N0Ronly.gif",dateString,hourString,i]];
NSURLRequest* request = [NSURLRequest requestWithURL:fileUrl];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,NSData * data,NSError * error) {
if ([data length] >0 && error == nil){
UIImage *image = [UIImage imageWithData:data];
if(image!=nil){
[imgArray addObject:image];
}
}else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
}else if (error != nil){
NSLog(@"Error = %@", error);
}
}];
}
NSLog(@"%@",imgArray);
self.animationImages = [[NSArray alloc] initWithArray:imgArray];
self.animationDuration = 1.0f;
self.animationRepeatCount = 0;
[self startAnimating];
}
答案 0 :(得分:0)
for(int i=0;i<=5;i++){
NSURL *fileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://radar.weather.gov/ridge/Conus/RadarImg/southeast_%@_%@%i8_N0Ronly.gif",dateString,hourString,i]];
NSURLRequest* request = [NSURLRequest requestWithURL:fileUrl];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,NSData * data,NSError * error) {
if ([data length] >0 && error == nil){
UIImage *image = [UIImage imageWithData:data];
if(image!=nil){
[imgArray addObject:image];
}
}else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
}else if (error != nil){
NSLog(@"Error = %@", error);
}
//Use your imgArray inside the completion handler block, right now you are using it outside the block
NSLog(@"%@",imgArray);
self.animationImages = [[NSArray alloc] initWithArray:imgArray];
self.animationDuration = 1.0f;
self.animationRepeatCount = 0;
[self startAnimating];
}];
}
希望这对你有用。