我有一个的NSDictionary数据如下:订单NSArray的使用对象
(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;
};
}
我整理基础上,名这些对象,如果他们没有名,我将使用用户名。要做到这一点,我创建了一个新的的NSDictionary与名和ID,并在方法结束时,我用名排序。对它们进行排序的代码如下:
- (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 ";
},
)
任何时候你使用构造函数'stringWithFormat:@“%@”'你犯了一个错误。除了浪费内存和处理器时间之外,这绝对无所不能。不要这样做。只需使用原始字符串,而不使用stringWithFormat,它只是以一种处理器密集型的方式创建一个不需要的字符串副本。 – 2014-10-29 17:21:48