我有一个非常有趣的问题。
在我的一个类中,我声明了一个非常简单的实例方法 - (NSDictionary)字典; 这是以这种方式实现的:
- (NSDictionary *)dictionary {
return [NSDictionary dictionaryWithObjectsAndKeys:
self.userID, @"id",
self.userName, @"name",
self.userSurname, @"sName",
self.userNickname, @"nName",
self.userPassword, @"pwd",
[NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000], @"birthday",
self.userSex, @"sex",
self.userEmail, @"email",
self.userLanguage, @"locale",
[NSNumber numberWithLongLong:self.userCoin], @"coin",
self.userRate, @"rate",
[NSNumber numberWithDouble:self.userCoordinate.latitude], @"lat",
[NSNumber numberWithDouble:self.userCoordinate.longitude], @"lon",
self.userPlaces, @"userPlaces",
nil];
}
声明这个方法没有@" userPlaces"我的返回字典中的键(self.userPlace显然是有价值的并且充满了对象)。
所以我改变了一下这样的方法:
- (NSDictionary *)dictionary {
NSMutableDictionary *toReturn = [NSMutableDictionary dictionary];
[toReturn setValue:self.userID forKey:@"id"];
[toReturn setValue:self.userName forKey:@"name"];
[toReturn setValue:self.userSurname forKey:@"sName"];
[toReturn setValue:self.userNickname forKey:@"nName"];
[toReturn setValue:self.userPassword forKey:@"pwd"];
[toReturn setValue:[NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000] forKey:@"birthday"];
[toReturn setValue:self.userSex forKey:@"sex"];
[toReturn setValue:self.userEmail forKey:@"email"];
[toReturn setValue:self.userLanguage forKey:@"locale"];
[toReturn setValue:[NSNumber numberWithLongLong:self.userCoin] forKey:@"coin"];
[toReturn setValue:self.userRate forKey:@"rate"];
[toReturn setValue:[NSNumber numberWithDouble:self.userCoordinate.latitude] forKey:@"lat"];
[toReturn setValue:[NSNumber numberWithDouble:self.userCoordinate.longitude] forKey:@"lon"];
[toReturn setValue:self.userPlaces forKey:@"userPlaces"];
return [NSDictionary dictionaryWithDictionary:toReturn];
}
所有密钥现在都出现在输出字典中!!!
这个问题让我很难理解,但我的问题是...... 有没有理由第二种方法比第一种方法更好?
我没有找到理由。
答案 0 :(得分:38)
[NSDictionary dictionaryWithObjectsAndKeys:
在找到nil
值时停止添加对象。
因此,您尝试在第一个代码中添加的对象之一很可能是nil。
答案 1 :(得分:7)
类似于下面的代码的东西解决了我的问题,同样的例外:
(NSMutableDictionary *)dictionary {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
self.userID, @"id",
self.userName, @"name",
self.userSurname, @"sName",
self.userNickname, @"nName",
self.userPassword, @"pwd",
[NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000], @"birthday",
self.userSex, @"sex",
self.userEmail, @"email",
self.userLanguage, @"locale",
[NSNumber numberWithLongLong:self.userCoin], @"coin",
self.userRate, @"rate",
[NSNumber numberWithDouble:self.userCoordinate.latitude], @"lat",
[NSNumber numberWithDouble:self.userCoordinate.longitude], @"lon",
self.userPlaces, @"userPlaces",
nil];
}