0

I often see in code the use of instance variables in different ways, I am not sure how to use them properly in objective-c. For example, in the following code, I declare the property imagePicker, which also creates the underlying instance variable _imagePicker.

@interface ViewController ()

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end

@implementation ViewController


-(void)initVariables{


}

When do I properly use the following? I have seen all three ways utilized in code, but do not understand the circumstances in which to use them.

self._imagePicker =

_imagePicker.property 

imagePicker.property
Michael
  • 6,561
  • 5
  • 38
  • 55

1 Answers1

4

I don't think any of the snippets you have listed will work...

self._imagePicker //Does not exists, it should be self.imagePicker

_imagePicker.property //There is no property "property" in object of type UIImagePickerController

//And the same error goes for your last example.

I'm guessing you have seen it two ways that are common. self.imagePicker or _imagePicker. These two access points do different things and are useful in different circumstances.

self.imagePicker = actually calls the [self setImagePicker:object] method. If you don't create this method manually the method will be synthesized for you by the compiler.

_imagePicker = just sets the object directly without calling that method.

So where this becomes a problem is if you implement your own [self setImagePicker:] method. Inside that method you would do something like:

-(void)setImagePicker:(UIImagePickerController*)controller
{
    self.imagePicker = controller;
}

This code is very bad. Since self.imagePicker = gets changed by the compiler to [self setImagePicker:] then you are calling that method recursively to no end. Your program crashes right there (after quite a while of 100% cpu usage and no UI functionality). Instead you should use the instance variable directly when you write the setter method:

-(void)setImagePicker:(UIImagePickerController*)controller
{
    _imagePicker = controller;
}

I hope this explains a little.

jlehr
  • 15,557
  • 5
  • 43
  • 45
Putz1103
  • 6,211
  • 1
  • 18
  • 25
  • I know those won't work, I used 'property as an example,' I could have used mediaTypes. Thanks for the answer, I understand now) – Michael May 02 '14 at 18:57
  • Those are methods, not functions. And the modern compiler will synthesize property methods without `@synthesize`. – jlehr May 02 '14 at 18:57
  • To avoid the recursive issue, I can simple use '_imagePicker' when setting the variable within the 'setImagePicker' method, correct? – Michael May 02 '14 at 19:00
  • @Nikita Yes, that is how you would do that correctly. But if you don't need to do extra code inside that method I would not create it manually, let the compiler do it for you. – Putz1103 May 02 '14 at 19:04