Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images into NSArray using initWithObjects crashes but not with an NSMutableArray?

I'm doing some lazy loading of images into an array when the app has loaded. I have tried using an NSMutableArray and an NSArray (I don't need to alter the array once it's been created) but the latter crashes on me.

...
[self performSelectorInBackground:@selector(loadImageArrays) withObject:nil];
...

- (void)loadImageArrays {

    NSAutoreleasePool *pool;
    pool = [[NSAutoreleasePool alloc] init];
    NSString *fileName; 

    imageArray = [[NSMutableArray alloc] init];
    for(int i = 0; i <= x; i++) {
        fileName = [NSString stringWithFormat:@"image_0000%d.png", i];
        [imageArray addObject:[UIImage imageNamed:fileName]];
    }
    [pool drain];
}

vs

NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
imageArray = [[NSArray alloc] initWithObjects:
            [UIImage imageNamed:@"image_00000.png"],
            [UIImage imageNamed:@"image_00001.png"],
            [UIImage imageNamed:@"image_0000X.png"],
                    nil];
[pool drain];

NSZombieEnabled = YES tells me that [UIImage retain] was sent to deallocated instance when using the latter code-snippet. Both arrays have (nonatomic, retain) property in my h-file. Why are the images not being retained by the NSArray?

like image 891
hwaxxer Avatar asked Mar 08 '26 02:03

hwaxxer


1 Answers

UIImage is part of UIKit, which is not thread safe. For example, the method imageNamed: could corrupt the global name-image dictionary that the UIImage class uses for caching.

You have to use Core Graphics if you want to load images on a background thread.

Edit to answer your comment:

You can load PNG files with:

CGDataProviderRef source = CGDataProviderCreateWithURL((CFURLRef)url);
CGImageRef image = CGImageCreateWithPNGDataProvider(source, NULL, NO, kCGRenderingIntentDefault);
CFRelease(source);

A CGImage is a core foundation object and can be stored in an NSArray. You can then make a UIImage from it (on the main thread, of course):

[[UIImage alloc] initWithCGImage:image]
like image 78
Nikolai Ruhe Avatar answered Mar 11 '26 08:03

Nikolai Ruhe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!