I'm trying to go through a mutable array searching for a given string. If the string does not exist in the array, I want to add it ONCE. The issue I'm having right now is that the string gets added a number of times.
Here's the code I'm using
NSMutableArray *array;
array=[self.开发者_如何学CstoredData getNames];
if([array count]!=0){
for (int i=0; i<[array count]; i++) {
MyUser *user=[array objectAtIndex:i];
if(![user.firstName isEqualToString:self.nameField.text]){
[array addObject: object constructor method goes here];
[self.storedData setNames:array];
}
}
}
else{
[array addObject:object constructor method];
[self.storedData setNames:array];
}
Any help would be greatly appreciated.
You're adding new string on each loop iteration when enumerating array which is clearly wrong. When enumerating array just set a flag indicating whether string was found and after the loop ad your string to array if it was not:
NSMutableArray *array = [self.storedData getNames];
BOOL found = NO;
for (MyUser *user in array){
if(![user.firstName isEqualToString:self.nameField.text]){
found = YES;
break;
}
}
if (!found){
[array addObject: object constructor method goes here];
[self.storedData setNames:array];
}
精彩评论