Can Objective-C's new literal syntax mimic the addObject?
Asked Answered
S

1

8

I know that I can do this to :

NSMutableArray *objects = [@[objectOne, objectTwo] mutableCopy];
NSObject *someObject = [NSObject new];
objects[0] = someObject;

But is there a way for the new literal syntax to mimic addObject:?

Silsbye answered 22/3, 2013 at 16:16 Comment(0)
S
13

As I was writing this, I tried out this bit of code and it worked like a charm. It isn't exactly documented, but I think this is a safe way to handle addObject: with the new literal syntax.

NSMutableArray *objects = [@[] mutableCopy];
NSObject *someObject = [NSObject new];
objects[objects.count] = object;
Silsbye answered 22/3, 2013 at 16:16 Comment(6)
It actually is documented to do this way in the setObject:atIndexedSubscript: methodPlover
"If the index is equal to count the element is added to the end of the array, growing the array."Rachaba
Why would anyone want to do this?Kimberlite
For science, that's why.Silsbye
That, and the possibility of re-setting, then adding elements to an array in a loop without doing a bounds check :) Nice.Quartile
Would be good to have a objects[] = object, please add it Apple! :DLapful

© 2022 - 2024 — McMap. All rights reserved.