iphone - 每个 IBOutlet 都应该有一个属性吗?

标签 iphone ios cocoa-touch iboutlet

我们为一个变量创建属性,以便在其他 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/

相关文章:

iphone - 将文件名中包含字符串的应用程序包中的所有文件加载到 NSMutableArray 中?

iphone - 用 UIPickerView 优雅地替换 iPhone 键盘

iphone - UIAlertView 按钮按下导致崩溃,而其他所有按钮都工作正常

ios - 我是否需要增量获取 CloudKit 更改和订阅?

ios - 在 ios 中创建自定义标注

objective-c - UITableViewCell setSelectedBackground 无法正确显示框架

iphone - 核心数据和核心位置

javascript - iOS 上的事件 'onDeviceMotion' 有任何限制吗?

ios - 注册推送通知没有得到任何响应

ios - Restkit:使用 xml 进行对象映射