客观c类为什么返回 - (id)而不是它自己的类 [英] objective c classes why return -(id) instead of it's own class

查看:198
本文介绍了客观c类为什么返回 - (id)而不是它自己的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C#背景,你初始化一个类,然后像这样返回

I came from a C# background where you initialize a class and then return itself like so

public class MyClass{
  public int Id;
  public string Name;
}

MyClass classInstance = new MyClass();
:
:

我知道c#与目标c不同,但我我试图找到一种方法来轻松理解客观c如何使转换变得更容易。并找出最佳实践。

I know c# is different from objective c, but I'm trying to find a way to easily understand how objective c works to make the transition easier. And figure out best practices too.

无论如何,我的问题是为什么你必须创建一个方法并返回一个id而不是返回它自己的类型?像这样:

Anyway, my question is why doyou have to create a method and return an "id" instead of returning it's own type? Like so:

- (id)initWithID:(NSInteger)id name:(NSString *)name
{
    self = [self init];
    if (self) {
        self.ID = id;
        self.name = name;
    }
    return self;
}

感谢您的时间

推荐答案

由于继承,在初始化方法中返回类型为 id 的对象。

You return an object of type id in initialization methods because of inheritance.

这样想:你有一个类 Foo 的对象。它有一个名为 initWithWidgets 的init方法。现在,您创建一个 Foo 的子类,并将其命名为 Bar 。根据继承规则,它可以访问 initWithWidgets 方法。如果 initWithWidgets 的返回类型是 Foo ,那么 Bar class将无法使用它来初始化自己!返回类型将与您尝试实例化的对象不同。因此,如果你使用 id ,你会说这个对象的返回类型可以是任何类型,你对子类是安全的!

Think of it this way: You have an object of class Foo. It has an init method called initWithWidgets. Now, you create a subclass of Foo and name it Bar. By the rules of inheritance, it has access to the initWithWidgets method. If the return type for initWithWidgets was Foo, then your Bar class would be unable to use it to initialize itself! The return type would be different than the object you are trying to instantiate. Thus, if you use id, you're saying "the return type of this object can be of any type" and you're safe for the subclasses!

这篇关于客观c类为什么返回 - (id)而不是它自己的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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