原语的通用返回类型 [英] Generic return type for primitives

查看:65
本文介绍了原语的通用返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似于您可以使用 NSObject 作为任何对象的返回类型的任何原语"的返回类型?我尝试使用 id,但编译器给了我一个错误,提示它试图将原始类型转换为引用.

Is there a return type for "any primitive" similar to the way you can use NSObject as the return type for any object? I tried using id, but the compiler was giving me an error that it was trying to convert a primitive to a reference.

这就是我想要做的.:

-(void)setObject:(NSObject*)obj forKey:(NSString*)key {
    [sharedInstance.variables setObject:obj forKey:key];
}


-(NSObject*)getObjectForKey:(NSString*)key {
    return [sharedInstance.variables objectForKey:key];
}


-(void)setValue:(???)value forKey:(NSString*)key {
    [sharedInstance.variables setValue:value forKey:key];
}


-(???)getValueForKey:(NSString*)key {
    return [sharedInstance.variables valueForKey:key];
}

我想到的替代方法是使用单独的方法(getIntForKey、getFloatForKey 等)来访问值.

The alternative that I have though of is to use separate methods (getIntForKey, getFloatForKey, etc.) to access the values.

推荐答案

我最终解决了这个问题.最终的解决方案是为每种类型使用单独的访问器/修改器方法.所以现在我有 setIntForKeysetBoolForKeygetIntForKeygetBoolForKey 等.我不能调用一种方法来设置值而另一种方法来检索它们.然而,优点是多方面的.因为编译器知道该方法在编译时期望什么对象或原始类型,所以我获得了对所有这些方法的编译时检查.此外,我不必担心将检索到的值转换为其原始类型(显然返回的 NSObjects 是另一回事).

I eventually worked through this. The ultimate solution was to have separate accessor/mutator methods per type. So now I have setIntForKey, setBoolForKey, getIntForKey, getBoolForKey, etc. The drawback is quite obvious, in that I can't call one method to set values and another to retrieve them. The advantages are numerous, however. Because the compiler knows what object or primitive type the method is expecting at compile time, I gain compile time checking for all of these methods. Additionally, I don't have to worry with casting the retrieved values to their primitive types (obviously the returned NSObjects are a different story).

这篇关于原语的通用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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