什么是自我?我应该在什么时候使用它? [英] what is self? when should i use it?

查看:135
本文介绍了什么是自我?我应该在什么时候使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否向我解释目标-C 2.0中的自我?什么时候和在哪里应该使用?
与java中的定义类似?

can you explain me the self in the objective-C 2.0 ? when and where should i use? is it similar with this definition in java?

推荐答案

self 指的是你正在工作的当前类的实例,是的,它是类似于这个在Java。

self refers to the instance of the current class that you are working in, and yes, it is analagous to this in Java.

如果要对该类的当前实例执行操作,则使用它。例如,如果你在一个类上编写一个实例方法,并且想要调用该实例上的一个方法来执行某些操作或检索某些数据,那么可以使用 self

You use it if you want to perform an operation on the current instance of that class. For example, if you are writing an instance method on a class, and you want to call a method on that same instance to do something or retrieve some data, you would use self:

int value = [self returnSomeInteger];

这也经常用于实例上的访问器方法(即setter和getter),特别是setter方法,如果他们实现额外的功能,而不只是设置一个实例变量的值,这样你不必重复该代码一遍又一遍当你想设置该变量的值,例如:

This is also often used for accessor methods on an instance (i.e. setters and getters) especially with setter methods, if they implement extra functionality rather than just setting the value of an instance variable, so that you do not have to repeat that code over and over when you want to set the value of that variable, for example:

[self setSomeVariable:newValue];

self 是在类的初始化期间。示例代码可能如下所示:

One of the most common uses of self is during initialization of a class. Sample code might look like:

- (id)init
{
    self = [super init];

    if(self!=nil) {
        //Do stuff, such as initializing instance variables
    }

    return self;
}

这会调用超类的(通过 super )initializer,这是如何链接初始化发生在类层次结构。然后,返回的值被设置为 self ,但是,因为超类的初始化器可能返回一个不同于超类的对象。

This invokes the superclass's (via super) initializer, which is how chained initialization occurs up the class hierarchy. The returned value is then set to self, however, because the superclass's initializer could return a different object than the superclass.

这篇关于什么是自我?我应该在什么时候使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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