如何将字符串对象添加到NSMutableArray

时间:2012-12-12 06:54:07

标签: objective-c nsmutablearray

我有一个名为randomSelection的NSMutableArray:

NSMutableArray *randomSelection;

如果符合某些条件,我会尝试向此数组添加字符串:

[randomSelection addObject:@"string1"];

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

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

然而,没有任何内容输出到错误日志,我无法弄清楚原因。

任何帮助/提示都表示赞赏。

6 个答案:

答案 0 :(得分:64)

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

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

答案 1 :(得分:5)

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

您需要先分配它。

答案 2 :(得分:4)

首先使用以下语句&分配数组。然后是对象。

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

这肯定会解决你的问题。

答案 3 :(得分:3)

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

答案 4 :(得分:2)

试试这个:

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

答案 5 :(得分:0)

斯威夫特:

MapLoader.Listener mapLoaderListener = new MapLoader.Listener() {
  public void onUninstallMapPackagesComplete(MapPackage rootMapPackage,
     MapLoader.ResultCode mapLoaderResultCode) {
  }
  public void onProgress(int progressPercentage) {
  }
  public void onPerformMapDataUpdateComplete(MapPackage rootMapPackage,
     MapLoader.ResultCode mapLoaderResultCode) {
  }
  public void onInstallationSize(long diskSize, long networkSize) {
  }
  public void onInstallMapPackagesComplete(MapPackage rootMapPackage,
      MapLoader.ResultCode mapLoaderResultCode) {
  }
  public void onGetMapPackagesComplete(MapPackage rootMapPackage,
      MapLoader.ResultCode mapLoaderResultCode) {

      // This method will be called after MapLoader#getMapPackages()
      // is called
      // You can use the rootMapPackage object to find the Id's to
      // pass to installMapPackages()

  }
  public void onCheckForUpdateComplete(boolean updateAvailable,
    String currentMapVersion,String newestMapVersion,
          MapLoader.ResultCode mapLoaderResultCode) {
  }
};

MapLoader mapLoader = MapLoader.getInstance();

mapLoader.addListener(mapLoaderListener);
mapLoader.getMapPackages();

OR

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