开发者

iOS Searching an array for a string and adding it if missing

开发者 https://www.devze.com 2023-04-06 21:13 出处:网络
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

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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消