I have this piece of code I use to test animations in iOS. The goal is to load 4 png's and animate them in an UIImageView. I have an NSMutableArray imageNames in which I keep the paths to the images. It gets filled correctly. Then when I try to use it to create UIImage it works the first time, but it returns nil afterwards. Why does this happen? I can't wrap my head around this.
for (NSInteger i = 0; i < imageNames.count; i++) { NSString *name = [imageNames objectAtIndex:i]; [images addObject:[UIImage imageNamed:name]]; } Here's the full code:
- (void)viewDidLoad { [super viewDidLoad]; UIView *test = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 50, 50)]; test.backgroundColor = [UIColor purpleColor]; [self.view addSubview:test]; self.view.backgroundColor = [UIColor greenColor]; NSMutableArray *imageNames = [[NSMutableArray alloc] initWithCapacity:4]; NSString *basePath = @"/Users/johndoe/Desktop/soa/SoA/SoA/Models/firefly/"; // Load images for (NSInteger i = 0; i < 4; i++) { NSMutableString *fullPath = [NSMutableString stringWithString:basePath]; [fullPath appendFormat:@"SMALL_0000_Capa-%ld.png", i + 1]; [imageNames addObject:fullPath]; // [fullPath appendString:@"SMALL_0000_Capa-1.png"]; } NSMutableArray *images = [[NSMutableArray alloc] init]; for (NSInteger i = 0; i < imageNames.count; i++) { NSString *name = [imageNames objectAtIndex:i]; [images addObject:[UIImage imageNamed:name]]; } // Normal Animation UIImageView *animationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 95, 86, 193)]; animationImageView.animationImages = images; animationImageView.animationDuration = 0.5; [self.view addSubview:animationImageView]; [animationImageView startAnimating]; }
UIImage imageNamed:only takes a base filename - no path, no extension. The named image should be an image found in your app's resource bundle. Why are you passing a full path? Why are you hardcoding a path on your computer for an iOS app? All of this is wrong.