What is File’s owner in XIB in this case?

2019-04-14 12:47发布

问题:

I've searched for similar questions for quite a while, most of which mentioned UIViewController's xib stuff. I tried to add a xib file for my custom viewController model,and found that its Xib’s File’s Owner should be my custom viewController model's class--that is reasonable. But why the situation differs when i create a xib for my UIView model-- an example as follows:

I create my UIView model which named "KWView"(KWView.h and KWView.m) then i create xib for this model, initializing it by

 KWView *oneView = [[[NSBundle mainBundle] loadNibNamed:@"KWView" owner:nil options:nil ]lastObject];

This Xib’s File’s Owner name is “NSObject”(then i try any other more,whatever i choose, it runs smoothly),and there, i choose the view’s Custom Class as “KWView”[This xib named "KWView.xib"]

Questions are :

1.Whatever i change the Xib’s File’s Owner name of my custom view, it works. If so, what the work does this File’s Owner do here, or saying, why can this happen?

2.Generally, should i set the custom view's Xib’s File’s Owner to my custom view's class or the viewController's class which this view is going to be added to ? or just set it "NSObject"?

回答1:

The answer to your question depends how you intend to extract the view from the nib at nib-load time. You are going to extract it, as you have helpfully shown us, like this:

KWView *oneView = 
    [[[NSBundle mainBundle] loadNibNamed:@"KWView" owner:nil options:nil]
        lastObject];

That means you aren't using the owner: for anything here — it is nil. Therefore you can leave the nib's file's owner at NSObject.

The purpose of the File's Owner is to permit you to establish, in the nib, Action and Outlet connections between the view (or its subviews) and the object that will be the real owner at load time — like a view controller (owner) and its view (the main view of the view controller). But in your case, there is no such real owner and no such Action or Outlet connections.