I've read every similar question, but have determined either I'm doing something stupid (possible) or I fail to grasp the NSArray
method containsObject:
I'm trying to setup a UITableView
that contains saved "favorites"; locations that are kept as a custom class called "MapAnnotations." This contains stuff like coordinates, title, an info field, and a couple of other parameters. I'm successfully saving/retrieving it from a NSUserDefaults
instance, but can't seem to successfully detect duplicate objects held in my NSMutableArray
.
Here's the relevant code:
-(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];
}
}
}
I've tried enumerating through the _myFavs
array, checking for matches on specific fields (get errors for enumerating through something mutable), tried to copy to a straight array... tried to use indexOfObject:
..