How do you compare 2 NSMutableArray ?
Different people might say this is a duplicate question, but i haven’t found a solution to my problem after viewing most of the SO question.
There is a Person object, and it has the Fields Name, Age, Rank
I have a MutableArray which will save the data from NSUserDefaults. then it will see if the NSMutableArray is contains that particular object. if not it will add it to NSUserDefaults.
There is some problem when i am adding the person object to NSUserDefaults (I am adding the person object through an array, see code).
When i print [data count] it is always 0. So it might not be getting added to NSUserDefaults properly. Or i might be doing some mistake.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults ) {
NSArray *arr= [userDefaults objectForKey:@"person"];
data = [NSMutableArray arrayWithArray:arr];
NSLog (@"%i ", [data count]);
if (! [data containsObject:self.person] ) {
[data addObject:self.person];
NSArray *personarr= [NSArray arrayWithArray:data];
[userDefaults setObject:personarr forKey:@"person"];
[userDefaults synchronize];
If you get an array from
NSUserDefaults, it will never be the same pointer, as any current object (like self.person).. so this won’t ever work. Comparing objects with==compares their memory adresses.If you want to compare them, use their contents. (eg.
[[person objectForKey: @"Name"] isEqualToString: [person2 objectForKey: @"Name"]]). So you should do it in a loop and check, if the name of the new person is already existing.Also,
arrayWithArrayis NOT a initializer ofNSMutableArray.So if it should be mutable, do it like that:
And if your count is always zero, check the actual array contents and look whats inside.
E.g. like this: