【问题标题】:How to add string objects to NSMutableArray如何将字符串对象添加到 NSMutableArray
【发布时间】:2012-11-29 20:09:57
【问题描述】:

我有一个名为 randomSelection 的 NSMutableArray:

NSMutableArray *randomSelection;

如果满足某些条件,我会尝试将字符串添加到该数组中:

[randomSelection addObject:@"string1"];

然后我尝试输出字符串,以确定它是否添加了它:

NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);

但是没有任何东西输出到错误日志中,我不知道为什么。

感谢任何帮助/提示。

【问题讨论】:

  • 您确定满足添加字符串的特定条件吗?否则,也许你应该试试 NSLog(@"%@", test);
  • 是的,符合标准。在我放置的 NSLog(test) 下方: NSLog("Made It!");并且正在显示。
  • 我是否需要初始化 NSMutable 数组并分配足够的空间或其他什么?我认为这就是这个 addObject 函数的意义所在,所以我不必这样做。
  • @David Brunow 请在放置任何 cmets 或 ans 之前阅读问题......这家伙没有分配“NSMutableArray *randomSelection;”,所以他期望如何获得数组对象......跨度>

标签: objective-c nsmutablearray


【解决方案1】:

我认为您缺少为数组分配内存。所以试试这个

NSMutableArray *randomSelection = [[NSMutableArray alloc] init];
[randomSelection addObject:@"string1"];
NSString *test = [randomSelection objectAtIndex:0];
NSLog(test);

【讨论】:

  • @SamBo 确实忘记分配内存并对其进行初始化。现在数组被声明了,但没有定义。
  • @ophychius 也有同样的问题。至少现在我知道我需要先为数组分配内存。但是没有更通用的方法来指定你只想在数组中添加字符串吗?
【解决方案2】:
NSMutableArray *randomSelection =  [[NSMutableArray alloc]init];
[randomSelection addObject:@"string1"];

你需要先分配它。

【讨论】:

  • 为我工作..谢谢你的朋友..:)
【解决方案3】:

首先使用以下语句分配数组,然后在其中分配对象。

NSMutableArray *randomSelection =  [[NSMutableArray alloc] init];
[randomSelection addObject:[NSString stringWithFormat:@"String1"]];
[randomSelection addObject:[NSString stringWithFormat:@"String2"]];
NSLog(@"Array - %@", randomSelection);

这肯定会解决你的问题。

【讨论】:

    【解决方案4】:

    试试这个:

    NSMutableArray *randomSelection = [[NSMutableArray alloc]init]; 
    [randomSelection addObject:@"string1"];
    

    【讨论】:

      【解决方案5】:

      只需分配您的 NSMutableArray。你的问题会得到解决的。

      【讨论】:

        【解决方案6】:

        斯威夫特:

        var randomSelection: [AnyObject] = [AnyObject]()
        randomSelection.append("string1")
        let test: String = randomSelection[0] as! String
        print(test)
        

        let array : NSMutableArray = []
        array.addObject("test String")
        print(array)
        

        【讨论】:

          猜你喜欢
          • 2012-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-25
          • 1970-01-01
          • 2014-05-25
          相关资源
          最近更新 更多