Search code examples
iphoneiosobjective-calassetslibrary

How to compare two ALAssets?


I have some trouble with compare two ALAssets object. I have two NSMutableArray: selectedImages and mutableAssets. I store there ALAssets object. But when i want to compare this assets it doesnt work for isEqual or containsObject method, only when i compare it by their url it works:

        ALAsset *asset1 = [self.mutableAssets objectAtIndex:0];
        ALAsset *asset2 = [self.selectedImages objectAtIndex:0];

        NSLog(@"%@", asset1);
        NSLog(@"%@", asset2);

        if([self.selectedImages containsObject:[self.mutableAssets objectAtIndex:0]]) {
            NSLog(@"the same1");
        }
        if([asset1 isEqual:asset2]) {
            NSLog(@"the sames2");
        }
        if([asset1.defaultRepresentation.url isEqual:asset2.defaultRepresentation.url]) {
            NSLog(@"the same3");
        }

Gives only this line:

ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=E8947286-22E2-42E4-A904-14D940A387B3&ext=JPG
ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=E8947286-22E2-42E4-A904-14D940A387B3&ext=JPG
the same3

Why it happens?


Solution

  • seems like Assets don't implement isEqual:

    I would not check the defaultRep's URL though... two different assets may have the same defaultRep in a way

    I'd go with the ALAssetPropertyAssetURL for iOS 6+ or ALAssetPropertyURLs for ios4&5

    --- you could wrap this in a category even!

    @interface ALAsset (isEqual)
    - (NSURL*)defaultURL;
    @end
    
    @implementation ALAsset (isEqual)
    
    - (NSURL*)defaultURL {
         if([[[UIDevice currentDevice] systemVersion] floatValue]>=6.0)
         {
              return [self valueForKey: ALAssetPropertyAssetURL];
         }
         else
         {
               return self.defaultRepresentation.url;
         }
    }
    - (BOOL)isEqual:(id)obj {
        if(![obj isKindOfClass:[ALAsset class]]) 
            return NO;
    
        NSURL *u1 = [self defaultURL];
        NSURL *u2 = [obj defaultURL];
    
        return ([u1 isEqual:u2]);
    }
    

    for iOS 4 and 5 and 6 and up