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

时间:2014-03-04 18:29:59

标签: ios objective-c nsmutablearray

我已经阅读了每个类似的问题,但确定要么我正在做一些愚蠢的事(可能)或者我没有抓住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];
        }
    }
}

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

或者您可以使用NSOrderedSet(或者如果需要可变),它可以用来完成所有的集合成员函数,以及具有NSArray期望的所有索引类型函数。

当您需要实际的NSArray版本时,可以使用- array将其转换为数组,其中可枚举将无效。