ObjC中的自我是什么?我什么时候应该使用它? [英] What is self in ObjC? When should i use it?

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

问题描述

self在Objective-C中是什么意思?我应该在何时何地使用它? 它与Java中的this相似吗?

What does self mean in Objective-C? When and where should I use it? Is it similar to this in Java?

推荐答案

self指的是您正在使用的当前类的实例,是的,它类似于Java中的this.

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),该初始化器是在类层次结构中如何进行链式初始化的.然后,将返回值设置为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.

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

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