Objective-C中的类对象和实例变量 [英] Class Objects and Instance Variables in Objective-C

查看:116
本文介绍了Objective-C中的类对象和实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用这个概念包围我的头。我将从这本书中得到引用:

I'm having a hard time wrapping my head around this concept. I'll take the quote exactly from the book:


类对象也继承自层次结构中它们上面的类。但因为他们没有实例变量(只有实例),所以它们只继承方法。

Class objects also inherit from the classes above them in the hierarchy. But because they don’t have instance variables (only instances do), they inherit only methods.

如果我错了, ,但类对象是这样:

Correct me if I'm wrong, but a class object would be this:

NSString *aString = [[NSString alloc]initWithString:@"abc.."];

类对象在这种情况下是 * aString - 我到目前为止是否正确?

The class object in this case is *aString -- am I correct so far?

令我困惑的是上面引用的第二句话,但因为他们没有实例变量实例do),它们只继承方法。

The thing that confuses me is the second sentence in the quote above, "But because they don’t have instance variables (only instances do), they inherit only methods."

我认为一个对象(在这种情况下 * aString NSString 类的实例。
上面的第二句话暗示着一个实例是不同的。

I thought that an object (in this case *aString) was the instance of the NSString class. The second sentence above is implying that an instance is something different. It's not making any sense to me.

推荐答案

您不正确。

NSString *aString = [[NSString alloc] initWithString:@"abc..."];

在这一行中,我们从左到右有:

In this line, we have, from left-to-right:


  • A类型: NSString *

  • 变量名称: aString

  • 作业

  • A >: NSString

  • 调用类方法: + alloc / li>
  • 对类方法的返回值调用实例方法: -initWithString:

  • 作为参数传递给实例方法的对象: @abc ...

  • A type: NSString *
  • A variable name: aString
  • an assignment
  • A Class: NSString
  • An invocation of a class method: +alloc
  • An invocation of an instance method on the return value of the class method: -initWithString:
  • An object being passed as a parameter to the instance method: @"abc..."

在Objective-C中, Class 实际上是一种对象。您可以以与实例相同的方式与它们进行交互,但由于它们是类,因此它们不能具有实例变量(因为根据定义,实例变量仅用于实例)。 只有方法。它们继承其他,这是如何实现对象继承。

In Objective-C, a Class is actually a kind of object. You can interact with them in many of the same ways that you can instances, but since they are "classes", they cannot have instance variables (since instance variables, by definition, are only for instances). Classes only have methods. They inherit from other Classes, and this is how object inheritance is implemented.

有关这方面的更多信息,由Greg Parker发表的这篇真棒博客: http://www.sealiesoftware.com/blog /archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

For more information on this, check out this awesome blog post by Greg Parker: http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

这篇关于Objective-C中的类对象和实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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