【问题标题】:adding a string followed by an int to an array将一个字符串后跟一个 int 添加到数组中
【发布时间】:2011-07-19 10:13:41
【问题描述】:

我对使用 Cocoa 的 Objective-C 非常陌生,我需要帮助。

我有一个 for 语句,其中我将 i 从 1 循环到 18,并且我想在此循环中向 NSMutableArray 添加一个对象。现在我有:

chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++)
{
    [chapterList addObject:@"Chapter"+ i];
}

我希望它添加对象,第 1 章、第 2 章、第 3 章...、第 18 章。我不知道如何做到这一点,或者即使有可能。有没有更好的办法?请帮忙

提前致谢,

【问题讨论】:

  • 你的意思是你想要Chapter 1Chapter 2等字符串?

标签: objective-c cocoa string nsmutablearray int


【解决方案1】:
chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++)
{
    [chapterList addObject:[NSString stringWithFormat:@"Chapter %d",i]];
}

祝你好运

【讨论】:

    【解决方案2】:

    试试:

    [chapterList addObject:[NSString stringWithFormat:@"Chapter %d", i]];
    

    在 Objective-C/Cocoa 中,您不能使用 + 运算符附加到字符串。您要么必须使用 stringWithFormat: 之类的东西来构建您想要的完整字符串,要么使用 stringByAppendingString: 之类的东西来将数据附加到现有字符串中。 NSString reference 可能是一个有用的起点。

    【讨论】:

      【解决方案3】:

      如果您想要只显示Chapter 1Chapter 2 的字符串,您可以这样做:

      chapterList = [[NSMutableArray alloc] initWithCapacity:18];
      for (int i = 1; i<19; i++) {
          [chapterList addObject:[NSString stringWithFormat:@"Chapter %d",i]];
      }
      

      完成后不要忘记释放数组,因为您正在调用alloc

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-13
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多