1

How can I write the following code:

self.box = [[NSMutableArray alloc] initWithObjects:
                    [NSMutableArray arrayWithObjects:_imageView1,_imageView2,_imageView3,nil],
                    [NSMutableArray arrayWithObjects:_imageView4,_imageView5,_imageView6,nil],
                    [NSMutableArray arrayWithObjects:_imageView7,_imageView8,_imageView9,nil],
                    nil];

with the modern syntax?

1
  • 1
    Do you really need mutable arrays? It's quite unlikely for UI elements. Commented Nov 8, 2017 at 16:39

2 Answers 2

4

I will self answer: for NSMutableArray there is no literal syntax, so you have to write:

  self.box = [@[
    [@[ _imageView1, _imageView2, _imageView3 ] mutableCopy],
     [@[ _imageView4, _imageView5, _imageView6 ] mutableCopy],
     [@[ _imageView7, _imageView8, _imageView9 ] mutableCopy]
    ] mutableCopy];
Sign up to request clarification or add additional context in comments.

Comments

1

If you wish to do it with fewer brackets than your own answer you can use:

self.box = @[
             @[_imageView1, _imageView2, _imageView3].mutableCopy,
             @[_imageView4, _imageView5, _imageView6].mutableCopy,
             @[_imageView7, _imageView8, _imageView9].mutableCopy
           ].mutableCopy;

2 Comments

I wouldn't use dot notation here since mutableCopy is a normal method and not a property: - (id)mutableCopy; Although it is shorter it can lead to confusing code like: 'someObject.someReallyExpensiveMethod' and 'NSMutableArray.alloc.init.count'.
@MaartenFoukhar - I almost wrote in the answer that some might not like this as mutableCopy is declared as a method with a property getter-like type, but decided not to - didn't want to upset sensitive Swiftees ;-) Joking aside I think they key word is like, and yes it can be abused if taken to extreme but this case doesn't. (I'll admit I often write .new as well, but never .alloc.init!)

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.