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

目前正在做:

- (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.
       }
    }


我做对了吗?还是我想的可能?我是否可以在需要时使同一数组可变,因为我的条件是true时才需要可变数组。

最佳答案

您应该在以下情况下更改代码:

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;
}

10-08 03:22