我什么时候应该使用“self”?关键词?

发布于 2024-09-30 15:35:11 字数 222 浏览 6 评论 0原文

我什么时候应该在 iPhone 开发应用程序中使用 self 表达式?假设我有 2 个字段: UITextField *text1;NSString *str1; 保留并合成。

当我访问这两个字段中的任何一个时,什么时候应该使用 self.text1self.str1

When should I be using the self expression in my iphone development applications? say i have 2 fields: UITextField *text1; and NSString *str1; retained and synthesized.

when i am accessing either of these 2 fields, when should i and when should i not use self.text1 and self.str1 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

岁月静好 2024-10-07 15:35:11

self 不是关键字,而是表达式。此外,您可以在任何时候想要引用自己或直接引用自己的方法或属性时使用它。我所说的“你自己”当然是指你正在操作的类的实例。

self is not a keyword, it is an expression. Additionally, you use it any time you want to refer to a method or property on yourself, or yourself directly. By "yourself" I am of course, referring to the instance of the class you are operating in.

一张白纸 2024-10-07 15:35:11

在某些情况下,通常不鼓励使用 self. 表达式来访问属性。 通常你 总是 使用 自我 对于任何财产的访问。这是最安全、最简单的方式。特别是如果你使用了retain,那么内存管理将会为你完成。

此规则有两个例外:

  • 任何 init 方法。
  • dealloc中。

在这两种情况下,您都在处理一个部分初始化的对象。在这里使用 setter 或 getter 时可能会出现一些副作用——因为它们是方法,因此可能会被覆盖。

例如,采用一个类 A,其属性 foo 已被类 B 子类化。子类 B 添加了一个属性 bar 并覆盖了 foo 的 setter。现在,您的 init 方法调用 setFoo:,因为您使用了 self.foo = ... 以及一些初始值。然而,子类也会访问此 setter 中的 bar 值。但在这种情况下,可能会发生 bar 从未初始化并指向某些任意数据的情况。 在 init 中调用 setter 会导致崩溃,尽管在​​您自己的代码中概率可能不会太高。

There are certain circumstances where it's generally discouraged to use the self.-expression to access a property. Normally you always use self for any access of a property. It's the most secure and uncomplicated way. Especially if you used retain, then memory management will be done for you.

The two exceptions from this rule:

  • Any init method.
  • In dealloc.

In both cases you are dealing with an partially initialized object. There are some side effects that may occur when using setters or getters here -- because they are methods and hence may be overridden.

For example, take a class A with a property foo that has been subclassed by class B. The subclass B adds an property bar and overrode the setter for foo. Now your init-method calls setFoo:, because you used self.foo = ... with some initial value. The subclass, however, also accesses the value of bar in this setter. But in this case, it may happen that bar has never been initialized and points at some arbitrary data. Calling a setter in init my cause crashes, although the probability may not be too high in your own code.

生来就爱笑 2024-10-07 15:35:11

在您的示例中,当您使用 self 时,您不会直接访问实例变量,而是访问您定义的属性。

考虑这个例子:

@interface Foo : NSObject {
   NSString *_bar;
}

@property (nonatomic, retain) NSString *bar;

@end

@implementation Foo
@synthesize bar = _bar;
-(void)baz {
   _bar = @"ivar";  //accessing the ivar
   self.bar = @"property"; //accessing the ivar via the property
}

@end

一般来说,如果您使用属性,则没有理由使用 ivar。这具有自动保留和保留的额外好处。为您释放价值。

但也存在其他情况,即您的属性将具有 readonly 修饰符。在这些情况下,有必要直接访问您的 ivars 才能设置它们的值。

In your example you aren't directly accessing instance variables when you use self, instead you're accessing the properties you've defined.

Consider this example:

@interface Foo : NSObject {
   NSString *_bar;
}

@property (nonatomic, retain) NSString *bar;

@end

@implementation Foo
@synthesize bar = _bar;
-(void)baz {
   _bar = @"ivar";  //accessing the ivar
   self.bar = @"property"; //accessing the ivar via the property
}

@end

In general if you're using properties, there's little reason to utilize the ivar. This has the added benefit of automatically retaining & releasing values for you.

But other cases exist when your properties will have a readonly modifier. In these cases it's necessary to directly access your ivars in order to set their values.

落花随流水 2024-10-07 15:35:11

如果您有自定义 getter,有时在方法调用中使用 self 也是一个好主意。使用 Core Data 的应用程序中的 managedContext 对象就是一个很好的例子。如果您通过 self.managementContext 引用它,则可以覆盖该对象并将其设置为 nil 所需的内容。请参阅创建使用 Core Data 的应用程序时由 XCode 生成的代码。

下面是 XCode 生成的代码示例,实际上:

@interface YourAppDelegate : NSObject <UIApplicationDelegate>
{
@private
    NSManagedObjectContext *managedObjectContext_;
}


@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;



@implementation ContractionTimerAppDelegate

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {

    if (managedObjectContext_ != nil) {
        return managedObjectContext_;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext_ = [[NSManagedObjectContext alloc] init];
        [managedObjectContext_ setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext_;
}

@end

It's also a good idea to use self within a method call sometimes if you have a custom getter. The managedContext object within a Core Data-using application is a good example. If you refer to it by self.managedContext, you can override and set the object to what it needs to be if it's nil. Refer to the code generated by XCode when creating an application that uses Core Data.

Here is an example of the code generated by XCode, actually:

@interface YourAppDelegate : NSObject <UIApplicationDelegate>
{
@private
    NSManagedObjectContext *managedObjectContext_;
}


@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;



@implementation ContractionTimerAppDelegate

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {

    if (managedObjectContext_ != nil) {
        return managedObjectContext_;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext_ = [[NSManagedObjectContext alloc] init];
        [managedObjectContext_ setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext_;
}

@end
红墙和绿瓦 2024-10-07 15:35:11

如果你“综合”变量,你应该“自我”。变量。小经验法则

if you "synthesize" the variable, you should "self." the variable. little rule of thumb

围归者 2024-10-07 15:35:11

我对 Objective-C 一无所知,但这看起来很像其他语言(如 C++、C#、Java、PHP 等)中的 this 关键字。如果是这样,那么我的建议是始终使用它。这样,如果您(不小心)定义了具有相同名称的局部变量,您的代码就不会中断。

然而,我还必须补充一点,这在某种程度上是一场宗教辩论,在程序员社区中曾有过激烈的争论。因此,请对这个建议持保留态度,并使用对您来说最有意义的任何内容。只要保持一致即可。

I don't know anything about objective-c, but this looks a lot like this keyword from other languages (like C++, C#, Java, PHP, and others). If so, then my advice is to use it always. That way, if you ever (accidentally) define a local variable with the same name, your code won't break.

However, I must also add, that this is somewhat of a religious debate with a history of flamewars in programmer communities. So take this advice with a grain of salt and use whatever seems to make most sense to you. Just be consistent about it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文