ios - Interface Builder 如何与私有(private) IBOutlet 交互?

标签 ios dependency-injection interface-builder private iboutlet

我看到 IB 的工作是取消归档 Nib 文件,加载 Nib 中的对象并将它们设置为 IBOutlet 属性。有些人甚至use IB as DI framework

但是 IBOutlet 可以是私有(private)的,我的意思是它可以在类扩展或实现部分中声明。那么IB如何与这些私有(private)IBOutlet进行交互呢?

@interface FPMovieBottomViewController ()

@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;

@end

最佳答案

如此处的注意中所述:Customizing Existing Classes

By adding the class extension shown above, redeclaring the uniqueIdentifier property as a readwrite property, a setUniqueIdentifier: method will exist at runtime on every XYZPerson object, regardless of whether other source code files were aware of the class extension or not.

The compiler will complain if code in one of those other source code files attempts to call a private method or set a readonly property, but it’s possible to avoid compiler errors and leverage dynamic runtime features to call those methods in other ways, such as by using one of the performSelector:... methods offered by NSObject. You should avoid a class hierarchy or design where this is necessary; instead, the primary class interface should always define the correct “public” interactions.

If you intend to make “private” methods or properties available to select other classes, such as related classes within a framework, you can declare the class extension in a separate header file and import it in the source files that need it. It’s not uncommon to have two header files for a class, for example, such as XYZPerson.h and XYZPersonPrivate.h. When you release the framework, you only release the public XYZPerson.h header file.

我已经突出显示了我们可以使用动态运行时修改现有类的部分。在 ruby​​ 或 python 等其他语言中,这称为 monkey-patching

有一篇关于此的好文章:monkeypatching-for-humans .但是,在给出的示例中,扩展只允许向现有类添加功能,而不是替换删除覆盖。在 objc 中,猴子修补的一个准确示例是方法调配。这并不总是有害的,因为开发人员一直在利用它来构建 Xcode 插件之类的东西,或者 mogenerator .

关于ios - Interface Builder 如何与私有(private) IBOutlet 交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259427/

相关文章:

ios - UIBarButtonItem 外观代理设置字体属性在 iOS 11 中不起作用

android - Dagger2.10+ : Inject ViewModel in Fragment/Activity which has run-time dependencies

ios - 在 Storyboard 中更改 iphone 4 和 iphone 5 之间的背景图像?

ios - 将ViewController的uiview换成xib

iphone - 同一个 UITextField 中的居中占位符,但大小不同

ios - 当应用程序在后台运行时,iOS 会删除 NSTemporaryDirectory 文件吗

java - Spring DI 同时有两个构造函数

ios - Xcode 6 中 IBOutlet 创建的新行为

ios - NavigationItem 按钮和 Edit mode 按钮分层次显示

c# - 不支持带有 Autofac 的 Net Core 3.0 抛出 IServiceProvider