我们为一个变量创建属性,以便在其他 View 中使用它。我们为 IBOutlets 做同样的事情。但并不总是为了使用它们。是否有必要为我们刚刚创建的每个 IBOutlet 创建属性?还是这样做只是一种好的做法?
最佳答案
我喜欢看它是否易于内存管理和外部访问。如果你需要从外部访问它,显然要创建一个属性。 (是的轻松内存管理,如果它很容易你就不会把它搞砸,如果你不把它搞砸它以后就不会成为一个错误)
80% 的时间我的 View Controller 有 IBOutlets 并且没有其他人访问它们,因此 ivars 工作。 问题是当你不使用@property 时,分配的值仍然保留。然后你需要记住释放它,即使你自己没有保留它,我发现这是违反直觉的。
出于这个原因,我通常对我不会更改的那些使用@property(分配),对其他一切使用@property(保留),并且从不将 IBOutlet 直接声明为 ivars。
例子:
@interface something : NSObject {
//This one needs to be RELEASED then set to nil in both viewDidUnload, and dealloc.
IBOutlet UILabel * myLabel;
//also cannot be accessed outside of "something" class (technically it can, but don't do that)
//I NEVER declare my outlets this way.
}
//This one can just be set to nil in viewDidUnload and dealloc
@property (nonatomic, retain) UILabel * myOtherLabel;
//it can also be accessed from mySomething.myOtherLabel by any other class.
//This one just works. I don't own it, the view owns it, so I don't retain/release.
@property (nonatomic, assign) UILabel * myOtherOtherLabel;
//It also provides access to outsiders.
//I wouldn't recommend using this type if you want to change the value though.
关于iphone - 每个 IBOutlet 都应该有一个属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6897414/