我有一个方法initWithNSDictionary:
- (id) initWithNSDictionary:(NSDictionary*)countryInfo_
{
self = [super init];
if(self) {
NSLog(@"Country Info = %@",countryInfo_);
self.code = [countryInfo_ valueForKey:@"countryCode"];
self.name = [countryInfo_ valueForKey:@"countryName"];
self.continent = [countryInfo_ valueForKey:@"continentName"];
self.region = [countryInfo_ valueForKey:@"region"];
self.currencyCode = [countryInfo_ valueForKey:@"currencyCode"];
self.population = [countryInfo_ valueForKey:@"population"];
}
NSLog(@"code %@", code);
return self;
}
我通过以下方式访问此方法:
Country *country = [[Country alloc] initWithNSDictionary:jsonObject];
之后我通过以下方式在标签中打印此值:
countryCode.text = [NSString stringWithFormat:@"Country Code = %@", country.code];
当我在控制台中记录它时,我得到:
NSLog(@"Currency Code = %@", currencyCode.text);
Currency Code = Currency Code = (
BRL
)
在标签的实际设备屏幕上,我只是得到:
Country Name = (
我希望输出如下:
Currency Code = BRL
CountryInfo_:
Country Info = (
{
areaInSqKm = "8511965.0";
capital = "Bras\U00edlia";
continent = SA;
continentName = "America meridionale";
countryCode = BR;
countryName = Brasile;
currencyCode = BRL;
east = "-32.392998";
fipsCode = BR;
geonameId = 3469034;
isoAlpha3 = BRA;
isoNumeric = 076;
languages = "pt-BR,es,en,fr";
north = "5.264877";
population = 201103330;
south = "-33.750706";
west = "-73.985535";
}
)
国家代码打印:
code (
BR
)
为什么会这样?
答案 0 :(得分:1)
我认为currencyCode的换行符为NSString
试试这个
currencyCode.text = [[[currencyCode.text stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];`
希望这有用。
答案 1 :(得分:1)
实际的CountryInfo_
是一个数组,而不是NSDictionary
。所以不要传递
Country *country = [[Country alloc] initWithNSDictionary:jsonObject];
尝试传递
Country *country = [[Country alloc] initWithNSDictionary:jsonObject[0]];
答案 2 :(得分:0)
尝试这样的事情
self.code = [[countryInfo_ objectAtIndex:0] objectForKey:@"countryCode"];
self.name = [[countryInfo_ objectAtIndex:0] objectForKey:@"countryName"];
self.continent = [[countryInfo_ objectAtIndex:0] objectForKey:@"continentName"];
self.region = [[countryInfo_ objectAtIndex:0] objectForKey:@"region"];
self.currencyCode = [[countryInfo_ objectAtIndex:0] objectForKey:@"currencyCode"];
self.population = [[countryInfo_ objectAtIndex:0] objectForKey:@"population"];