這是從ALAssetsLibrary加載圖像的靜態函數。如何在IOS5上使用NSConditionLock
它在IOS4.X上運行良好,但是在IOS5上它將停在行: 「[albumReadLock lockWhenCondition:WDASSETURL_ALLFINISHED];」
如何在IOS4.x和iOS5上使用NSConditionLock?
// loads the data for the default representation from the ALAssetLibrary
+ (UIImage *) loadImageFromLibrary:(NSURL *)assetURL {
static NSConditionLock* albumReadLock;
static UIImage *realImage;
// this method *cannot* be called on the main thread as ALAssetLibrary needs to run some code on the main thread and this will deadlock your app if you block the main thread...
// don't ignore this assert!!
NSAssert(![NSThread isMainThread], @"can't be called on the main thread due to ALAssetLibrary limitations");
// sets up a condition lock with "pending reads"
albumReadLock = [[NSConditionLock alloc] initWithCondition:WDASSETURL_PENDINGREADS];
// the result block
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
ALAssetRepresentation *rep = [myasset defaultRepresentation];
//NSNumber *orientation = [myasset valueForProperty:ALAssetPropertyOrientation];
CGImageRef iref = [rep fullResolutionImage];
NSNumber *orientation = [myasset valueForProperty:ALAssetPropertyOrientation];
UIImage *image = [UIImage imageWithCGImage:iref scale:1.0 orientation:[orientation intValue]];
realImage = [image retain];
// notifies the lock that "all tasks are finished"
[albumReadLock lock];
[albumReadLock unlockWithCondition:WDASSETURL_ALLFINISHED];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
//NSLog(@"NOT GOT ASSET");
//NSLog(@"Error '%@' getting asset from library", [myerror localizedDescription]);
// important: notifies lock that "all tasks finished" (even though they failed)
[albumReadLock lock];
[albumReadLock unlockWithCondition:WDASSETURL_ALLFINISHED];
};
// schedules the asset read
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:assetURL
resultBlock:resultblock
failureBlock:failureblock];
// non-busy wait for the asset read to finish (specifically until the condition is "all finished")
[albumReadLock lockWhenCondition:WDASSETURL_ALLFINISHED];
[albumReadLock unlock];
// cleanup
[albumReadLock release];
albumReadLock = nil;
// returns the image data, or nil if it failed
return realImage;
}