问题描述
我有一个简单的类 MyView
继承自 NSView
和实例变量 NSImage * image ;
中。类功能是在视图上绘制图像。
但是,在 -drawRect:
图像实例总是等于 nil
,如果它在 -init:
函数中初始化而不是 nil
如果它在 -awakeFromNib:
中初始化。日志显示 -init:
和 -awakeFromNib:
函数只调用一次。
-awakeFromNib:
默认重新初始化GUI组件
否。对于 awakeFromNib
没有默认实现。
您的问题是您覆盖了错误的初始化方法。 NSView
的是 initWithFrame:
。你的子类的简单 init
永远不会被调用,这就是为什么你的 image
ivar没有指向任何东西。 p>
您可以在 awakeFromNib
或 initWithFrame中初始化ivar:
。它没有什么区别。前者在后者之后调用,它作为一个点提供,您可以插入需要与您的nib中的其他对象交互的初始化代码(通过您的 IBOutlets
)。
I have a simple class MyView
inherited from NSView
and instance variable NSImage * image;
in it. Class functionality is to draw image on the view.
However, in -drawRect:
image instance always equal nil
, if it was initialized in -init:
function and not nil
if it was initialized in -awakeFromNib:
. Log shows both -init:
and -awakeFromNib:
functions are called only once.
Does -awakeFromNib:
reinitialize GUI component by default?
No. There is no default implementation for awakeFromNib
.
Your problem is that you're overriding the wrong initialization method. An NSView
's designated initializer is initWithFrame:
. Your subclass's plain init
never gets called, and that is why your image
ivar doesn't point to anything.
You can initialize that ivar in either awakeFromNib
or initWithFrame:
. It makes no difference. The former is called after the latter, and it is provided as a point where you can insert initialization code that needs to interact with other objects in your nib (via your IBOutlets
).
这篇关于NSView初始化:-init:vs. -awakeFromNib:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!