我正在尝试使用字典中的键添加一些值,以便向服务器发送请求。我在ios7上没有问题但是在ios5中创建字典时遇到问题,当空值输入时它不会插入该字符串或之后插入字典中。这是我的代码示例
NSLog(@"name:%@, address:%@,city:%@, state:%@, country:%@, postal:%@ ,phone:%@,age:%@, gender:%@",self.pop.firstNameTextField.text,self.pop.addressTextField.text, self.pop.cityTextField.text,[NSNumber numberWithInt:stateId],[NSNumber numberWithInt:countryId],self.pop.postalCodeTextField.text,self.pop.phoneNumberTextField.text,self.pop.ageTextField.text,self.pop.genderTextField.text);
NSDictionary *details = [NSDictionary dictionaryWithObjectsAndKeys:
self.pop.firstNameTextField.text,@"name",
self.pop.addressTextField.text,@"address",
self.pop.cityTextField.text,@"city",
[NSNumber numberWithInt:stateId],@"state",
[NSNumber numberWithInt:countryId],@"country",
self.pop.postalCodeTextField.text,@"postalCode",
self.pop.phoneNumberTextField.text,@"phoneNo",
self.pop.ageTextField.text,@"age",
self.pop.genderTextField.text,@"gender",
nil];
NSLog(@"MyDetails:%@",details);
在ios 7中记录结果:
name: GamerLegend,address:india,city:, state:1, country:1, postal: ,phone:, age:, gender:
MyDetails:
{
address = India;
age = "";
city = "";
country = 1;
gender = "";
name = "GamerLegend";
phoneNo = "";
postalCode = "";
state = 1;
}
ios5中的相同日志结果:
name: GamerLegend,address:haripad,city:(null), state:1, country:1, postal:(null) ,phone:(null), age:(null), gender:(null)
MyDetails:
{
address = India;
name = "GamerLegend";
}
我希望ios5的日志与ios7的日志相同。我做了一些搜索,我知道我可以预先比较它的值,检查它是否为null,然后添加到空字符串的字典。但那将是如此乏味。我想知道是否还有其他简单的解决方法。有没有更好的解决方案?
这是我目前的解决方案
-(void) checkForNull
{
if([self.pop.firstNameTextField.text length] == 0)
self.pop.firstNameTextField.text=@"";
if([self.pop.addressTextField.text length] == 0)
self.pop.addressTextField.text=@"";
if([self.pop.cityTextField.text length] == 0)
self.pop.cityTextField.text=@"";
if([self.pop.postalCodeTextField.text length] == 0)
self.pop.postalCodeTextField.text=@"";
if([self.pop.phoneNumberTextField.text length] == 0)
self.pop.phoneNumberTextField.text=@"";
if([self.pop.ageTextField.text length] == 0)
self.pop.ageTextField.text=@"18";
if([self.pop.genderTextField.text length] == 0)
self.pop.genderTextField.text=@"";
}
答案 0 :(得分:0)
如果符合您的要求,这应该有效:
创建一个EXPECTED键数组。然后循环遍历它并将其与字典中allKeys方法的输出进行比较。如果缺少一个键,你可以添加一个空字符串,[NSNull null]或任何漂浮你的船的缺失键。 (当然,你需要使字典可变)。
这样的事情:
for (NSString *expectedKey in allExpectedKeys) {
BOOL keyMissing = YES;
for (NSString *existingKey in [dictionary allKeys]) {
if ([expectedKey isEqualToString:existingKey]) {
keyMissing = NO;
break;
}
}
if (keyMissing) {
[dictionary setObject:[NSNull null] forKey:expectedKey];
}
}