检测NSMutable Array中包含的重复自定义对象

jam*_*rns 2 objective-c nsmutablearray ios

我读过的每一个类似的问题,但已经确定无论我在做一些愚蠢的事(可能),或者我不掌握NSArray方法containsObject:

我正在尝试设置UITableView包含已保存的"收藏夹"的内容; 保存为名为"MapAnnotations"的自定义类的位置.这包含坐标,标题,信息字段和其他一些参数.我成功地从一个NSUserDefaults实例保存/检索它,但似乎无法成功检测到我的重复对象NSMutableArray.

这是相关的代码:

-(void)doSetUp
{
//load up saved locations, if it exists

NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];

//if there are saved locations
if ([myDefaults objectForKey:@"savedLocations"]) {

    NSLog(@"file exists!");

      //get saved data and put in a temporary array
    NSData *theData = [myDefaults dataForKey:@"savedLocations"];
      //my custom object uses NSCode protocol
    NSArray *temp = (NSArray *)[NSKeyedUnarchiver unarchiveObjectWithData:theData];
    NSLog(@"temp contains:%@",temp);
      //_myFavs currently exists as a NSMutableArray property
    _myFavs = [temp mutableCopy];

}else{

    NSLog(@"File doesn't exist");
    _myFavs = [[NSMutableArray alloc]init];
}

    //_currLoc is an instance of my Mapnnotations custom class
        // which contains coordinates, title, info, etc.

if (_currLoc != nil) {

        //if this is a duplicate of a saved location

    if ([_myFavs containsObject:_currLoc]) {

        //pop an alert

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Sorry..." message:@"That location has already been saved." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
            //add location to end of myFavs array
        [_myFavs addObject:_currLoc];

        NSLog(@"myFavs now contains:%@",_myFavs);

        //write defaults

        NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:_myFavs];
        [myDefaults setObject:encodedObject forKey:@"savedLocations"];
        [myDefaults synchronize];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试枚举_myFavs数组,检查特定字段的匹配(通过可变的内容获取枚举错误),尝试复制到直接数组...尝试使用indexOfObject:..

das*_*ght 5

您可以将containsObject:方法与实现isEqual:方法的自定义对象一起使用.将此方法的实现添加到您的Mapnnotations类将解决此问题:

// In the .h file:
@interface Mapnnotations : NSObject
-(BOOL)isEqual:(id)otherObj;
...
@end

// In the .m file:
@implementation Mapnnotations
-(BOOL)isEqual:(id)otherObj {
    ... // Check if other is Mapnnotations, and compare the other instance
        // to this instance
    Mapnnotations *other = (Mapnnotations*)otherObj;
    // Instead of comparing unique identifiers, you could compare
    // a combination of other custom properties of your objects:
    return self.uniqueIdentifier == other.uniqueIdentifier;
}
@end
Run Code Online (Sandbox Code Playgroud)

注意:当您实现自己的isEqual:方法时,最好也实现该hash方法.这将允许您在哈希集中使用自定义对象并作为NSDictionary键.

  • 不要忘记也实现适当的`hash`方法.在类上创建`isEqual:`方法时,应始终执行此操作. (3认同)