Pregunta

Just when you think you understand something, you don't! :)

I understand that if I make a variable a property, I can access it anywhere in the Class and even set it from outside that class.

I thought if I didnt need it I could just make it an ivar. So I have a viewcontroller with about 5 UILabels. So in its viewDidLoad I say:

pharmacyName.text = self.receivedLocation.name;
    pharmacyTel1.text = @"556-7843";
    pharmacyTel2.text = @"991-2345";
    pharmacyTel3.text = @"800-0001";

When I have declared them like so in the .h file:

@interface DetailViewController : UIViewController{
    IBOutlet UILabel *pharmacyName;
    IBOutlet UILabel *pharmacyTel1;
    IBOutlet UILabel *pharmacyTel2;
    IBOutlet UILabel *pharmacyTel3;
}

@property (nonatomic,strong) MyLocation *receivedLocation;

@end
¿Fue útil?

Solución

No. Its not mandatory to create ivar as property. If you don't want to access it outside of class just use as it is. In ARC you can also declare your IBOutlet as below:

@interface DetailViewController : UIViewController{
    __weak IBOutlet UILabel *pharmacyName;
    __weak IBOutlet UILabel *pharmacyTel1;
    __weak IBOutlet UILabel *pharmacyTel2;
    __weak IBOutlet UILabel *pharmacyTel3;
}

This will keep a week reference of outlets. Here is detail of __weak and strong

Otros consejos

There are always many ways you can approach programming tasks and standards. Our group has started using a few coding standards. We like to put our instance variables that are NOT accessed from outside the class (and protocol statements) in the private interface in the .m file like this:

@interface DetailViewController() {
    NSString *value_;
}

@end

We also like to use @property for our instance ivars and declare those in the private interface as well like this:

@interface DetailViewController() {
}

@property (nonatomic, strong) IBOutlet UIlabel *pharmacyName;

@end

and then in your code, you would refer to this as self.pharmacyName. It seems to work pretty well with autocomplete, and with getting and setting. Also when you have thread safety issues, the nonatomic, strong behavior comes in handy.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top