When should I use the “self” keyword?

后端 未结 6 1774
执念已碎
执念已碎 2020-12-06 02:53

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

相关标签:
6条回答
  • 2020-12-06 02:59

    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.

    0 讨论(0)
  • 2020-12-06 03:02

    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.

    0 讨论(0)
  • 2020-12-06 03:05

    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.

    0 讨论(0)
  • 2020-12-06 03:06

    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
    
    0 讨论(0)
  • 2020-12-06 03:10

    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.

    0 讨论(0)
  • 2020-12-06 03:17

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

    0 讨论(0)
提交回复
热议问题