NSString stringWithFormat 返回类型,为什么是“id"? [英] NSString stringWithFormat return type, why is it "id"?

查看:55
本文介绍了NSString stringWithFormat 返回类型,为什么是“id"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么[NSString stringWithFormat] 方法返回一个id 类型?从我期望的名称来看,它返回一个 NSString,而不是一个通用指针.其他类遵循这个规则".例如 [NSNumber numberWithInt] 返回一个 NSNumber,而不是 id.

Why does the method [NSString stringWithFormat] return an id type? From the name I'm expecting it returns a NSString, not a generic pointer. Other classes follow this "rule". For example [NSNumber numberWithInt] returns a NSNumber, not an id.

我认为从类似于工厂方法的事实来看,这甚至是不合理的.

I think it's not even justified from the fact that is something like a factory method.

推荐答案

你提到了 NSNumber,这没有任何直接的子类,所以 numberWithInt: 是安全的返回一个 NSNumber*

You mention NSNumber, this doesn't have any direct subclasses, so it's safe for numberWithInt: to return a NSNumber*

NSString*(和其他类,例如 NSSet)返回类型 id 因为它们可以有子类 (NSMutableString> 和 NSMutableSet ),它们将继承这个方法.因此,这些继承的调用需要返回子类类型的实例,并且由于方法命名规则,您不能仅根据返回类型进行重载.因此,它们之间需要一个共同的类型,即 id.

NSString* (and other classes such as NSSet) return type id because they can have subclasses (NSMutableString and NSMutableSet respectively), which will inherit this method. As such, these inherited calls need to return an instance of the subclass's type, and due to the rules of method naming, you can't overload based on return type alone. As such, they need a common type between them all, which is id.

更新:最近的发展意味着关键字instancetype 现已可用.您可能已经注意到许多对 id 的引用现在被替换为 instancetype.该关键字向编译器提供了一个提示,即该方法的返回类型与该方法的接收者的类相同.

Update: Recent developments mean the keyword instancetype is now available. You may have noticed a lot of references to id are now replaced with instancetype. This keyword provides a hint to the compiler that the return type of the method is the same class of the receiver of the method.

例如(我强调一个例子,实际框架中可能并非如此):

For example (and I stress an example, this may not be the case in the actual framework):

NSArray:
- (instancetype)initWithArray:(NSArray*)array;

NSMutableArray:
// Inherits from NSArray

----

// Receiver is NSArray, method belongs in NSArray, returns an NSArray
[[NSArray alloc] initWithArray:@[]];

// Receiver is NSMutableArray, method belongs in NSArray, returns an NSMutableArray
[[NSMutableArray alloc] initWithArray:@[]];

这篇关于NSString stringWithFormat 返回类型,为什么是“id"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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