initWithFrame没有被调用,但awakeFromNib是 [英] initWithFrame not called, but awakeFromNib is
问题描述
我试图子类化NSOutlineView。这是我的代码:
I am trying to subclass NSOutlineView. Here is my code:
OutlineViewSublcass.h:
OutlineViewSublcass.h:
#import <Cocoa/Cocoa.h>
@interface OutlineViewSubclass : NSOutlineView {
}
@end
OutlineViewSubclass.m:
OutlineViewSubclass.m:
#import "OutlineViewSubclass.h"
@implementation OutlineViewSubclass
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
printf("debug A\n");
return self;
}
- (void)awakeFromNib
{
printf("debug B\n");
}
@end
调试输出为:
debug B
$ b b
为什么(id)initWithFrame:(NSRect)frame
被调用?
推荐答案
Cocoa控件实现NSCoding协议以从nib中取消归档。而不是使用initWithFrame:初始化对象,然后设置属性,initWithCoder:方法负责在使用Interface Builder配置的序列化属性加载控件时设置控件。这和使用NSCoding序列化任何对象的方法大致相同。
Cocoa controls implement the NSCoding protocol for unarchiving from a nib. Instead of initializing the object using initWithFrame: and then setting the attributes, the initWithCoder: method takes responsibility for setting up the control when it's loaded using the serialized attributes configured by Interface Builder. This works pretty much the same way any object is serialized using NSCoding.
如果你在一个没有实现NSCoding的nib中使用一个自定义NSView子类, ,在这种情况下,initWithFrame:将被调用。在这两种情况下,awakeFromNib将在对象加载后被调用,通常是在子类中执行附加初始化的好地方。
It's a little bit different if you stick a custom NSView subclass in a nib that doesn't implement NSCoding, in that case initWithFrame: will be called. In both cases awakeFromNib will be called after the object is loaded, and is usually a pretty good place to perform additional initialization in your subclasses.
这篇关于initWithFrame没有被调用,但awakeFromNib是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!