Search code examples
objective-cuiimagensarray

Why does my NSArray have zero objects?


I'm trying to add some UIImage objects to an array, but it's not working. I tried adding the images to an NSArray and for some reason, the array isn't holding anything?

Here is my code:

UIImage *a = [UIImage imageWithContentsOfFile:@"A.jpg"];
UIImage *b = [UIImage imageWithContentsOfFile:@"B.jpg"];
UIImage *c = [UIImage imageWithContentsOfFile:@"C.jpg"];
UIImage *d = [UIImage imageWithContentsOfFile:@"D.jpg"];
UIImage *e = [UIImage imageWithContentsOfFile:@"E.jpg"];
UIImage *f = [UIImage imageWithContentsOfFile:@"F.jpg"];

self.imageArray = [NSArray arrayWithObjects:a, b, c, d, e, f, nil];

int firstArrayCount = [self.array count];   
NSLog(@"%d objects in array 1", firstArrayCount);

int secondArrayCount = [self.imageArray count];
NSLog(@"%d objects in array 2", secondArrayCount);

Solution

  • UIImage *a = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"A" ofType:@".jpg"]];
    UIImage *b = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"B" ofType:@".jpg"]];
    UIImage *c = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"C" ofType:@".jpg"]];
    UIImage *d = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"D" ofType:@".jpg"]];
    UIImage *e = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"E" ofType:@".jpg"]];
    UIImage *f = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"F" ofType:@".jpg"]];
    
    NSArray *imageArray = [NSArray arrayWithObjects:a, b, c, d, e, f, nil];
    
    int secondArrayCount = [imageArray count];
    NSLog(@"%d objects in array 2", secondArrayCount);
    

    OR

    UIImage *a = [UIImage imageNamed:@"A.jpg"];
    UIImage *b = [UIImage imageNamed:@"B.jpg"];
    UIImage *c = [UIImage imageNamed:@"C.jpg"];
    UIImage *d = [UIImage imageNamed:@"D.jpg"];
    UIImage *e = [UIImage imageNamed:@"E.jpg"];
    UIImage *f = [UIImage imageNamed:@"F.jpg"];
    
    NSArray *imageArray = [NSArray arrayWithObjects:a, b, c, d, e, f, nil];
    
    int secondArrayCount = [imageArray count];
    NSLog(@"%d objects in array 2", secondArrayCount);