在if条件中使NSArray成为NSMutableArray

时间:2014-07-17 14:01:30

标签: ios objective-c arrays nsmutablearray nsarray

我的init方法中有一个数组,然后我希望在条件实际需要时创建一个可变数组。有可能吗?

目前正在做:

- (id)init
{
   self = [super init];

   if (self)
   {
      // [MyClass someMethod] in the below statement returns an array.
      NSMutableArray *someArray = [NSMutableArray arrayWithArray:[MyClass someMethod]];

      if (this condition is true)
      {
           [someArray addObject:@"XYZ"];
      }

     // Print someArray here.
   }
}

我想要做的是:

- (id)init
    {
       self = [super init];

       if (self)
       {
          // [MyClass someMethod] in the below statement returns an array.
          NSArray *someArray = @[[MyClass someMethod]];

          if (this condition is true)
          {
               // Make some array mutable here and then add an object to it.
               [someArray mutableCopy];
               [someArray addObject:@"XYZ"];
          }

         // Print someArray here.
       }
    }

我做得对吗?或者我在想什么?我可以在需要时使相同的数组变为可变,因为在我的情况下,只有当我的条件为if时才需要它是可变的。

2 个答案:

答案 0 :(得分:1)

如果条件:

,您应该更改代码
if (this condition is true)
{
     // Make some array mutable here and then add an object to it.
     NSMutableArray *mutableArray = [someArray mutableCopy];
     [mutableArray addObject:@"XYZ"];
     someArray = mutableArray.copy;
}

答案 1 :(得分:0)

这个怎么样?

{
   NSArray *array;
   if(condition)
   {
     NSMutableArray *mutaArray = [NSMutableArray arrayWithArray:[MyClass someMethod]];
     [mutaArray addObject:@"XYZ"];
     array=mutaArray;
   }
   else
     array=[MyClass someMethod];

}