Прыжки здесь, потому что, хотя я думаю, что вы должны работать над кодом самостоятельно первым, я думаю, что Миро ответ более сложный, чем требует проблема, и хотя мне нравится идея использования предикатов в ответе Грега, вот 3-е решение, которое (1) не потребовало бы, чтобы вы изменили структуру данных и (2) ссылались на необходимые циклы ...
Способ Я бы это сделал: создайте NSMutableArray, затем начните добавлять имена пользователей по порядку. Если NSMutableArray уже содержит имя пользователя, не добавляйте еще один экземпляр имени пользователя, а вместо этого объединяйте информацию о словаре.
ex.
// Note: I'm calling your array of user dictionaries userArray.
// Create a username array to store the usernames and check for duplicates
NSMutableArray *usernames = [[NSMutableArray alloc] init];
// Create a new userArray to store the updated dictionary info, merged
// entries et. al.
NSMutableArray *newUserArray = [[NSMutableArray alloc] init];
// Go through the array of user dictionaries
for (NSDictionary *userDict in userArray) {
// If the usernames array doesn't already contain the username,
// add it to both the usernames array and the newUserArray as is
if (![usernames containsObject:[userDict objectForKey:@"username"]]) {
[usernames addObject:[userDict objectForKey:@"username"]];
[newUserArray addObject:userDict];
}
// Otherwise, merge the userArray entries
else {
// Get a mutable copy of the dictionary entry at the first instance
// with this username
int indexOfFirstInstance = [usernames indexOfObject:[userDict objectForKey:@"username"]];
NSMutableDictionary *entry = [[newUserArray objectAtIndex:indexOfFirstInstance] mutableCopy];
// Then combine the "text" or whatever other values you wanted to combine
// by replacing the "text" value with the combined text.
// (I've done so with a comma, but you could also store the value in an array)
[entry setValue:[[entry objectForKey:@"text"] stringByAppendingString:[NSString stringWithFormat:@", %@", [userDict objectForKey:@"text"]]] forKey:@"text"];
// Then replace this newly merged dictionary with the one at the
// first instance
[newUserArray replaceObjectAtIndex:indexOfFirstInstance withObject:entry];
}
}
Вам необходимо попробовать их комбинировать, а затем, если у вас есть проблемы, покажите код и обратитесь за помощью. Начните с поиска и регистрации дубликатов. Затем посмотрите на слияние. – Wain