如果这是一个菜鸟问题,我很抱歉。
我一直在关注关于地图工具包的this教程,我偶然发现了这行代码
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];这是不寻常的原因,至少对我来说是因为它缺少带有%@标志的nsstring。本教程声称我们正在将纬度和经度信息添加到json中。
但是当我打印formatString和json时,输出是相同的。
我以前从未见过nsstring以这种方式使用。是否存在正在设置的隐藏变量?
有人能给我解释一下这个名为json的nsstring对象是如何包含这4个参数的吗?
发布于 2014-06-24 10:28:35
在代码中的其他地方,formatString必须定义如下:
NSString *formatString = @"latitude=%f, longitude=%f, %f = half the number of meters in a mile";确保您的测试如下所示:
NSLog(@"the format is %@ and the json is %@", formatString, json);它们看起来不应该是一样的。它们看起来相同的唯一方式是格式字符串不引用任何格式说明符,如下所示:
NSString *formatString = @"I'm a silly format with no percent format specifiers";发布于 2014-06-24 10:28:50
该formatString实际上包含%@的。它可能是这样的:
NSString *formatString = @"lat: %f | lon: %f | half-meters-per-mile: %f";
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];(请注意,我猜替换(%f)可能不正确)
至于它如何包含这四个参数,第一个参数之后的所有内容都是要添加到字符串中的值。第一个是一个字符串,表示将这些值放在哪里。
发布于 2014-06-24 13:00:48
如果你查看教程,下面的代码行写在你发布的内容之上-
NSString *jsonFile = [[NSBundle mainBundle] pathForResource:@"command" ofType:@"json"];
NSString *formatString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];从这里创建格式字符串,该文件将在教程的资源文件夹中可用。
https://stackoverflow.com/questions/24377382
复制相似问题