简体   繁体   English

我应该在iOS中设置ivars属性吗?

[英]Should I make my ivars properties in iOS?

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. 我想如果我不需要它,我可以把它变成一个ivar。 So I have a viewcontroller with about 5 UILabels. 所以我有一个带有大约5个UILabel的viewcontroller。 So in its viewDidLoad I say: 因此,在其viewDidLoad中,我说:

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: 当我在.h文件中这样声明它们时:

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

@property (nonatomic,strong) MyLocation *receivedLocation;

@end

No. Its not mandatory to create ivar as property. 否。将ivar创建为属性不是强制性的。 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: 在ARC中,您还可以如下声明您的IBOutlet:

@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 这是__weak and strong的细节

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: 我们喜欢将不能从类(和协议语句)外部访问的实例变量放在.m文件的私有接口中,如下所示:

@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: 我们也喜欢用@property我们的实例变量实例,并宣布与私营接口以及这样的:

@interface DetailViewController() {
}

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

@end

and then in your code, you would refer to this as self.pharmacyName . 然后在您的代码中,将其称为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. 同样,当您遇到线程安全问题时,非原子性强行为也会派上用场。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM