Is it correct to use short syntax when initializing NSMutableArray?

自闭症网瘾萝莉.ら 提交于 2019-12-20 02:34:30

问题


Usually when we want to initialize NSMutableArray we use:

NSMutableArray *mArr = [[NSMutableArray alloc] initWithObjects: @"one", @"two", @"three", nil];

But, is it correct to use syntax like:

NSMutableArray *mArr = @[@"one", @"two", @"three"].mutableCopy;

I understand, that it will work a couple of nanoseconds longer. But I think the second way to be way more readable and I'm ready to sacrifice those nanoseconds.

Is it ok, to use this kind of construction? Does ARC clean that unused NSArray, that I'm using to get a mutable copy? Isn't it going to be a leak?


回答1:


But I think the second way to be way more readable

Personally, I find it more confusing, and even more confusing since you are using mutableCopy as if it was a property. Correct, correct, but totally misleading IMHO.

Why not just take advantage of inheritance?

NSMutableArray *ma = [NSMutableArray arrayWithObjects:@"foo", @"bar", nil];

Sometimes collections which are mutable by default would be of more use. * sigh *




回答2:


Yes, it's ok to initialize your mutable array that way, if you are willing (as you indicated) to pay the performance cost. ARC will clean everything up appropriately. It won't leak.




回答3:


I usually use arrayWithArray.

NSMutableArray *foo = [NSMutableArray arrayWithArray:@[@"one", @"two", @"three"]];


来源:https://stackoverflow.com/questions/19186756/is-it-correct-to-use-short-syntax-when-initializing-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!