1

I was wondering how to add a string to a mutable array without having to change the original array. So I'm thinking I have to make a copy of the array argument and then add the string to that.

    -(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array
     {
       NSArray *newArray = [NSMutableArray arrayWithArray:array];

       [newArray arrayByAddingObject:[string]];

return array;
}

I get the error Expected identifer, not sure what that means.

2
  • simple do like [newArray arrayByAddingObject: string]; Commented Aug 2, 2016 at 4:52
  • 1
    your newArray is NSArray. It should be NSMutableArray !! Commented Aug 2, 2016 at 5:09

6 Answers 6

2

Use addObject method:

[array addObject:@"HEllo"];

Where array is a NSMutableArray

In you example method, it will be like this:

 -(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array
   return [array addObject:string];

  }
Sign up to request clarification or add additional context in comments.

Comments

1

u are creating the new array as just NSArray which is not mutable, and also the object u are trying to add is string why to use of [string], u can do like below,

 -(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array
  {
    NSMutableArray *newArray = [NSMutableArray arrayWithArray:array];
    [newArray addObject:string]; //no need of square brace, because string is an object 
    return newArray; //return the new array not the `array`
 }

1 Comment

it is not neccessary to reinitialize the array with arrayWithArray
0

You just need to do is

 -(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array
   return [array addObject:string];

  }

Comments

0

It should be like;

-(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array
    {
           [array addObject:string];

            return array;
    }

1 Comment

it is not neccessary to reinitialize the array with arrayWithArray .
0

There are extra [] in the code, change it to:

[newArray arrayByAddingObject:string];

1 Comment

arrayByAddingObject reinitialize the array and add the new item to that, while the question only wants to add the item to the current array and reinitializing this is not neccessary
0

You can use like this

In Swift

func arrayByAddingString(string: String, array: NSMutableArray) -> {
array.addObject(String)
return array
}

In Objective C

-(NSMutableArray *)arrayByAddingString:(NSString *)string toArray:(NSMutableArray *)array{
[array addObject:string];    
return array;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.