Invalid attempt to access ALAssetPrivate past the lifetime of its owning ALAssetsLibrary… WTF?

After the upgrade to iOS 5 and a code refactoring to make use of ARC, I was testing my app and receiving a strange error:

invalid attempt to access ALAssetPrivate past the lifetime of its owning ALAssetsLibrary

this because, I wasn’t aware of an ALAssetsLibrary‘s fact: (quote from Apple’s reference)

The lifetimes of objects you get back from a library instance are tied to the lifetime of the library instance.

This line of text should be displayed inside a warning box to catch developers attention, in fact it is an essential point to understand to create a reliable application that access to device’s media library! The point is that we have to ensure that an instance of ALAssetsLibrary is persisted in memory until we make use of ALAssets retrieved with it. To ensure this, I added a static method to retrieve a shared instance of that class (more or less like a singleton):

+ (ALAssetsLibrary *)defaultAssetsLibrary {
	static dispatch_once_t pred = 0;
	static ALAssetsLibrary *library = nil;
	dispatch_once(&pred, ^{
		library = [[ALAssetsLibrary alloc] init];
	});
	return library; 
}

So, I can refer to it using [MyAssetsManager defaultAssetsLibrary] through my classes and I can use threads (NSOperations an NSOperationQueues) without having to use “trick” like performSelectorOnMainThread.