如果方法的返回类型为NSArray,将返回值类型从NSMutableArray转换为NSArray是一种好习惯吗? [英] Is it good practice to convert return value type from NSMutableArray to NSArray if return type of method is NSArray?

查看:36
本文介绍了如果方法的返回类型为NSArray,将返回值类型从NSMutableArray转换为NSArray是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,如果我返回NSMutableArray而不是方法的返回类型NSArray,则不会收到任何警告或编译错误.

In the following code, I don't get any warning or compile error if I return NSMutableArray instead of NSArray which is the method's return type.

但是,使用像下面的代码这样的-copy方法将返回值转换为NSArray是一种好习惯吗?
还是我应该返回NSMutableArray?

But is it good practice to convert return value to NSArray by using -copy method like the following code?
Or should I return NSMutableArray?

+(NSArray *)returnImutableArray {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    [arr addObject:@"a"];
    [arr addObject:@"b"];

    //return arr; // no warning
    return [arr copy];
}

推荐答案

我认为这本质上是个人喜好.通过在返回数组之前复制该数组,可能会导致性能下降(可能很小).好处是,您将完全防止结果突变.但是,我通常不会麻烦.由于该方法的声明返回类型为 immutable NSArray,因此,如果您尝试在其上调用NSMutableArray的突变方法之一,则编译器会警告您,除非您竭力防止这种情况发生(通过强制转换到NSMutableArray).

I think this is essentially personal preference. You incur a (probably small) performance penalty by copying the array before returning it. The upside is that you'll completely prevent mutation of the result further down the line. However, I don't usually go to the trouble. Because the declared return type of the method is an immutable NSArray, the compiler will warn you if you try to call one of NSMutableArray's mutation methods on it unless you go out of your way to prevent that (by casting to NSMutableArray).

因此,简而言之,这是个人喜好,我个人通常不会打扰不可变的副本.

So, in short, it's personal preference and I personally don't generally bother with the immutable copy.

这篇关于如果方法的返回类型为NSArray,将返回值类型从NSMutableArray转换为NSArray是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆