首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不寻常的stringWithFormat:参数

不寻常的stringWithFormat:参数
EN

Stack Overflow用户
提问于 2014-06-24 10:19:58
回答 3查看 55关注 0票数 0

如果这是一个菜鸟问题,我很抱歉。

我一直在关注关于地图工具包的this教程,我偶然发现了这行代码

代码语言:javascript
复制
NSString *json = [NSString stringWithFormat:formatString,
                      centerLocation.latitude,
                      centerLocation.longitude,
                      0.5 * METERS_PER_MILE];

这是不寻常的原因,至少对我来说是因为它缺少带有%@标志的nsstring。本教程声称我们正在将纬度和经度信息添加到json中。

但是当我打印formatString和json时,输出是相同的。

我以前从未见过nsstring以这种方式使用。是否存在正在设置的隐藏变量?

有人能给我解释一下这个名为json的nsstring对象是如何包含这4个参数的吗?

EN

回答 3

Stack Overflow用户

发布于 2014-06-24 10:28:35

在代码中的其他地方,formatString必须定义如下:

代码语言:javascript
复制
NSString *formatString = @"latitude=%f, longitude=%f, %f = half the number of meters in a mile";

确保您的测试如下所示:

代码语言:javascript
复制
NSLog(@"the format is %@ and the json is %@", formatString, json);

它们看起来不应该是一样的。它们看起来相同的唯一方式是格式字符串不引用任何格式说明符,如下所示:

代码语言:javascript
复制
NSString *formatString = @"I'm a silly format with no percent format specifiers";

苹果公司的Here's a good intro on the topic

票数 2
EN

Stack Overflow用户

发布于 2014-06-24 10:28:50

formatString实际上包含%@的。它可能是这样的:

代码语言:javascript
复制
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)可能不正确)

至于它如何包含这四个参数,第一个参数之后的所有内容都是要添加到字符串中的值。第一个是一个字符串,表示将这些值放在哪里。

票数 1
EN

Stack Overflow用户

发布于 2014-06-24 13:00:48

如果你查看教程,下面的代码行写在你发布的内容之上-

代码语言:javascript
复制
 NSString *jsonFile = [[NSBundle mainBundle] pathForResource:@"command" ofType:@"json"];
 NSString *formatString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];

从这里创建格式字符串,该文件将在教程的资源文件夹中可用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24377382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档