【问题标题】:Last array value overwrite when adding NSMutableArray into another NSMutableArray将 NSMutableArray 添加到另一个 NSMutableArray 时覆盖最后一个数组值
【发布时间】:2012-11-26 07:23:37
【问题描述】:
    NSMutableArray *no1=[[NSMutableArray alloc]init];
    NSMutableArray *no2=[[NSMutableArray alloc]init];

    for(int i=0;i<3;i++)
    {
        for (int j=0;j<=i;j++)
        {
            NSString *no_str=[NSString stringWithFormat:@"%d",j];
            [no1 addObject:no_str];
        }
        [no2 addObject:no1];
        [no1 removeAllObjects];
    }
    NSLog(@"Final:%@",no2);

我得到如下输出:

决赛:( ( 0, 1、 2 ), ( 0, 1、 2 ), ( 0, 1、 2 ) )

但我需要这样的输出:

决赛:( ( 0 ), ( 0, 1 ), ( 0, 1、 2 ) )

请任何人帮助我。

【问题讨论】:

    标签: iphone objective-c nsstring nsmutablearray nsarray


    【解决方案1】:

    我假设您使用的是 ARC,所以这段代码可以正常工作。

    NSMutableArray *no1;
    NSMutableArray *no2=[[NSMutableArray alloc]init];
    
    for(int i=0;i<3;i++)
    {
        no1=[[NSMutableArray alloc]init];
        for (int j=0;j<=i;j++)
        {
            NSString *no_str=[NSString stringWithFormat:@"%d",j];
            [no1 addObject:no_str];
        }
        [no2 addObject:no1];
    }
    NSLog(@"Final:%@",no2);
    

    编辑:即使你分配 init no1 结果也是一样的。

    【讨论】:

      【解决方案2】:

      更新代码:-

      NSMutableArray *no1;
      
          NSMutableArray *no2=[[NSMutableArray alloc]init];
      
          for(int i=0;i<3;i++)
          {
              no1=[[NSMutableArray alloc]init];
              for (int j=0;j<=i;j++)
              {
                  NSString *no_str=[NSString stringWithFormat:@"%d",j];
                  [no1 addObject:no_str];
              }
              [no2 addObject:no1];
              [no1 release];
          }
          NSLog(@"Final:%@",no2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多