我有一个包含以下数据的 NSDictionary:
(lldb) po allFriends
{
71685207018702188 = {
id = 71685207018702188;
name = "mikeziri ";
username = mi;
};
93374822540641772 = {
id = 93374822540641772;
name = "Alan Weclipse";
username = zuka;
};
96553685978449395 = {
id = 96553685978449395;
name = "Monica Weclipse";
username = amonica;
};
96556113096345076 = {
id = 96556113096345076;
name = Xavier;
username = branko;
};
97017008427632119 = {
id = 97017008427632119;
name = "Dario Weclipse";
username = tarzan;
};
}
我根据名称对这些对象进行排序,如果它们没有名称,我将使用用户名。为此,我使用 name 和 id 创建了一个新的 NSDictionary,并在方法结束时按 name 对它们进行排序强>。对它们进行排序的代码如下:
- (NSArray*)orderFriends
{
NSMutableDictionary* newFriendsDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<[allFriends count];i++)
{
NSMutableDictionary* friendsDict = [[NSMutableDictionary alloc] init];
NSDictionary* friend = [allFriends objectForKey:[NSString stringWithFormat:@"%@", [sortedKeysFriends objectAtIndex:i]]];
if ([[friend objectForKey:@"name"] length] != 0)
{
[friendsDict setObject:[friend objectForKey:@"id"] forKey:@"id"];
[friendsDict setObject:[NSString stringWithFormat:@"%@", [friend objectForKey:@"name"]] forKey:@"name"];
}
else
{
[friendsDict setObject:[friend objectForKey:@"id"] forKey:@"id"];
[friendsDict setObject:[NSString stringWithFormat:@"%@", [friend objectForKey:@"username"]] forKey:@"name"];
}
[newFriendsDict setObject:friendsDict forKey:[NSNumber numberWithInt:i]];
}
NSArray* sp = nil;
sp = [[newFriendsDict allValues] sortedArrayUsingComparator:^(id obj1, id obj2){
NSString *one = [NSString stringWithFormat:@"%@", [obj1 objectForKey:@"name"]];
NSString *two = [NSString stringWithFormat:@"%@", [obj2 objectForKey:@"name"]];
return [one compare:two];
}];
return sp;
}
问题是最终结果是错误的:
(lldb) po sp
<__NSArrayI 0x160491a0>(
{
id = 93374822540641772;
name = "Alan Weclipse";
},
{
id = 97017008427632119;
name = "Dario Weclipse";
},
{
id = 96553685978449395;
name = "Monica Weclipse";
},
{
id = 96556113096345076;
name = Xavier;
},
{
id = 71685207018702188;
name = "mikeziri ";
},
)
最佳答案
区分大小写。使所有字符串变小或变大。
关于ios - 使用对象对 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26611722/