简体   繁体   中英

Obj-C - Check arrays within array for value?

I have a mutable array (self.arr1) that allows users to add objects to it. In this example, the self.arr1 is saved to NSUserDefaults, and looks like this:

(
    (
        (
         "Park"
        ),
         Corner Store
     ),
     "Cafe"
),
"Brewery"
)

I'm using the below code to add objects to self.arr1 (ie. when button is tapped, add objects to self.arr1), and then add self.arr1 to NSUserDefaults. I then want to check if "Park" is present in NSUserDefaults the next time the user opens the app. Even though it is present, the code is executing as if it's not there. It's almost as if because I'm initializing a new array everytime the button is tapped, it doesnt see that Park is indeed present in self.arr1. How can I have my code check all values inside self.arr1?

If I don't initialize the array when the button is tapped, it doesnt allow me to add objects at all, and the array returns null.

ViewController.m


-(void)viewDidLoad {
                                                      
    if ([self.placeDefaults containsObject:self.locationName.text]      {
                                 
                      // DO SOEMTHING

    }    
        
}
    
    
- (IBAction)collectPoints:(id)sender {
    
     self.arr1 = [[NSMutableArray alloc] init];
                                                                            
     [self.arr1 addObject:arrayOfPlaces];

     self.placeDefaults = [NSUserDefaults standardUserDefaults];
     [self.arr1 addObject:self.savedTitle];
                                                                            
     [self.placeDefaults setObject:self.arr1 forKey:@"visitedPlaces"];
    
}

Your code is adding the existing array as a nested array and then adding the new single string to the end.

All you need to do is make a mutable copy of the existing array and then add the new value. Also there is no need to use properties when local variables will do.

- (IBAction)collectPoints:(id)sender {
    
     NSMutableArray newArray = [[arrayOfPlaces mutableCopy];
                                                                            
     [newArray addObject:self.savedTitle];

     NSUserDefaults *placeDefaults = [NSUserDefaults standardUserDefaults];
                                                                            
     [placeDefaults setObject:newArray forKey:@"visitedPlaces"];
    
}

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