sye*_*dfa 1 nsmutablearray fast-enumeration ios
我有一个NSMutableArray包含Person类型的对象.Person对象包含NSString*name,NSString*dateStamp和NSString*testScore的参数.我想用快速枚举做的是检查NSMutableArray*testResults,查看是否存在具有相同名称参数的对象.
如果确实如此,那么我想NSMutableArray用我将要插入的具有dateStamp最新值的对象和testScore值替换现有对象.如果找到没有匹配name参数的对象,则只需插入我拥有的对象.
到目前为止,我的代码如下所示:
这是创建我要插入的对象的代码:
Person *newPerson = [[Person alloc] init];
[newPerson setPersonName:newName]; //variables newName, pass, and newDate have already been
[newPerson setScore:pass]; //created and initialized
[newPerson setDateStamp:newDate];
Run Code Online (Sandbox Code Playgroud)
这里是我尝试迭代NSMutableArray以查看是否已存在具有相同名称参数的对象的代码:
for (Person *checkPerson in personList) { //personList is of type NSMutableArray
if (newPerson.newName == checkPerson.name) {
//here is where I need to insert the code that replaces checkPerson with newPerson after a match has been found
}
else {
personList.addObject(newPerson); //this is the code that adds the new object to the NSMutableArray when no match was found.
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个非常复杂的问题,但我很困惑如何找到匹配,然后在不知道对象所在的索引的情况下替换实际对象.
您想使用indexOfObjectPassingTest查找匹配项:
NSInteger indx = [personList indexOfObjectPassingTest:^BOOL(Person *obj, NSUInteger idx, BOOL *stop) {
return [obj.name isEqualToString:newPerson.name];
}];
if (indx != NSNotFound) {
[personList replaceObjectAtIndex:indx withObject:newPerson];
}else{
[personList addObject:newPerson];
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用isEqualToString:比较两个字符串not ==.这个错误在这个论坛上被问过并回答了一百万次.
您的命名有些不一致.在这个问题中,你说Person对象有一个name属性,但是当你创建一个新人时你使用setPersonName,这意味着属性名是personName.我假设,只是在我的答案中命名.
| 归档时间: |
|
| 查看次数: |
1873 次 |
| 最近记录: |