我有一个使用 tableview 的简单问卷调查应用程序。当用户回答问题时,他们可以选择退后一步并更改他们所做的选择。这会导致结果中的答案加倍(选择存储在 NSmutableArray 中) 如何避免在数组中存储“双”结果?
6 回答
NSMutableArray *add= [[NSMutableArray alloc]init];
for (Item *item in addList){
if ([add containsObject:item])
{ // Do not add
}
else
[add addObject:item];
}
这里 addList 是对象列表
首先数组应该是 NSMutableArray 类型,然后检查要插入的对象是否存在
if([yourMutableArray containsObject:valueToBeStored]){
NSLog(@"do not add");
}
else{
[yourMutableArray addObject:valueToBeStored];
}
只需将您的更改NSMutableArray
为NSMutableSet
. 确保您的答案isEqual:
仅考虑正在回答的问题编号。也实施- (NSUInteger)hash
,但它可能没有。
I've made the assumption that in going back, the only way a user can go forward is to answer the question again and that the selections (answers) are stored in the array in the order they are answered.
In that case, all you need to do it remove the last object in the array each time you step back.
[selections removeLastObject];
It gets a bit more complicated if you're allowing them to move backwards and forwards, but essentially you hold onto the current index and decrement or increment it as you move backward or forward respectively.
You then use this index to replace the object in the array at the current index when the user selects a new answer.
[selections replaceObjectAtIndex:currentQuestionIndex withObject:newSelection];
Change your array to a NSMutableSet
or, if you need the sorting, use NSMutableOrderedSet
. This basically behaves like a NSMutableArray
but checks for double entries with isEqual:
.
在调用方法的地方使用以下代码...
[yourArray removeAllObjects];
我想这会对你有所帮助。