Obj-C:在方法中使用可变和返回非可变类 [英] Obj-C: using mutable and returning non mutable classes in methods

查看:152
本文介绍了Obj-C:在方法中使用可变和返回非可变类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在objective-C中,我发现自己创建了很多Mutable对象,然后将它们作为非可变对象返回。是我在这里做的方式,只是返回 NSMutableSet 作为 NSSet 一个好的做法?我想我可能应该指定我复制它。

In objective-C I find myself creating alot of Mutable objects and then returning them as non mutable objects. Is the way I am doing it here, simply returning the NSMutableSet as an NSSet a good practice? I was thinking maybe I should specify that i make a copy of it.

/**  Returns all the names of the variables used in a given
 *   program. If non are used it returns nil */
+ (NSSet *)variablesUsedInProgram:(id)program
{
    NSMutableSet* variablesUsed = [[NSMutableSet alloc]init];
    if ([program isKindOfClass:[NSArray class]]) {
        for (NSString *str in program)
        {
            if ([str isEqual:@"x"] || [str isEqual:@"y"] || [str isEqual:@"a"] || [str isEqual:@"b"])
                [variablesUsed addObject:str];
        }
    }
    if ([variablesUsed count] > 0) {
        return variablesUsed;
    } else {
        return nil;
    }
}


推荐答案

取决于你需要多少安全。如果你返回的对象作为NSSet它仍然是一个NSMutableSet,所以它可以很容易地被转换回一个和修改。

It depends how much safety you require. If you return the object as an NSSet it will still be an NSMutableSet, so it could easily be cast back to one and modified.

当然,如果您要创建公共API,我建议您返回一个副本。对于内部项目,也许方法签名已经使意图清楚了。

Certainly, if you're creating a public API, I'd recommend returning a copy. For in internal project, perhaps the method signature already makes the intention clear enough.

它值得注意的是,一般来说,返回一个副本的性能影响可以忽略不计 - 复制immutable实例是有效的,而每个拷贝发送到一个mutable-passing-as-immutable会创建另一个拷贝。所以我会说它的默认做法的好习惯。

Its, worth noting that, generally the performance impact of returning a copy is negligible - copying an immutable instance is effectively free whereas each copy sent to a mutable-passing-as-immutable will create another copy. So I would say its good practice to default to.

这篇关于Obj-C:在方法中使用可变和返回非可变类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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