简体   繁体   中英

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?

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

Background

containsObject: is determines whether anObject is present in the array by sending an isEqual: message to each of the array's objects (and passing anObject as the parameter to each isEqual: message).

isEqual: is inspect whether two objects are the same. If two objects are equal, they must have the same hash value. hash means a table address in a hash table structure.


so, if not containsObject also not isEqual. Derive the results if you want to your ALAsset override isEqual .

NSURL, isEqual is two NSURLs are considered equal if and only if they return identical values for both baseURL and relativeString.

if([[[asset1 defaultRepresentation].url absoluteString] isEqualToString:[[asset2 defaultRepresentation].url absoluteString]])
{
}
else
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM