1

In some books, Apple's code samples and internet resources I noted direct accessing to ivar instead of using synthesized accessors. It seems to me that it's very often for UILabel, UITextFiled and UITextView.

@interface MagicViewController : UIViewController {
    UITextField *aField;
}
@property (nonatomic, retain) UITextField *field; 


@implementation MagicViewController

@synthesize aField; 

- (void) superMethod 
{
    aField.text = @"Bla-bla-bla";

    NSString *string = [NSString stringWithString:aField.text];
    NSLog(@"Ho-ho-ho %@", string);

}

The question: Is it safe for some reasons? Why they don't use

- (void) superMethod 
{
    self.aField.text = @"Bla-bla-bla";

    NSString *string = [NSString stringWithString:self.aField.text];

    NSLog(@"Ho-ho-ho %@", string);

}

2 Answers 2

1

Not using the accessor guarantees that what you are accessing is, in fact, the ivar field, as a subclass could override .aField, supplying something else.

Wether this is what you want or not varies wildly.

That is one possible reason for the sample code to eschew accessors in favor of direct access, but precisely why it is done in any given case is not necessarily easy to know.

Another possible reason is that accessing the ivar is faster, and on iOS in particular, cycles are hard-won.

Sign up to request clarification or add additional context in comments.

1 Comment

If you have a time and wish, could you give me a short sample where it's necessary to access to ivar directly. It would be much appreciated, because I've seen "never ever use direct access to ivar". And it's clear about faster accessing.
0

Either way will work just fine in this particular case. They like to define everything out in references so you can see exactly what is happening.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.