How to instantiate an NSObject in the Interface bu

2019-07-29 23:42发布

问题:

Greetings,

I have a view based application project where I have created an NSObject class called "SquareClass". Now, from the Xcode's interface builder, I want to be able to instantiate that "SquareClass" into a square object with global scope, in such a way that, when I create actions from any UI controls(i.e textboxes, buttons etc...), I want to be able to call methods of that object within those actions.

example:

(void)MyAction1:(id)color
{
   [square setColor:color];
}

(void)MyAction2:(id)width
{
   [square setWidth:width];
}

As you can see, the square object needs to have a global scope. This might seems easy or maybe the wrong way of doing it for some of us. I've look through the web, and kinda found a way for a .nib file, not for a .xib file.

Any suggestion would be greatly appreciated. Thanks a lot.

Yohann.

ps: This is my first post EVER, be indulgent.

回答1:

Firstly, a NIB file is, for all intents and purposes, the same as an XIB file; it’s just a compiled version of a XIB file.

Now, to create an object derived from NSObject in your NIB/XIB, simply drag an NSObject from the library window into your file. Then on the Identity Inspector change the class to your custom class.

If you define methods like this:

- (IBAction)myAction:(id)sender

you’ll be able to hook them up in Interface Builder.

Having said all that, it’s difficult to tell whether what you’re doing is the right thing to do at all. It sounds to me like you should be using an NSViewController subclass so have a look at the documentation for that.

You should also make sure you understand what view, controller and model objects are. There’s plenty of literature on this.



回答2:

If you create a class extending UIView, then you can make the File's Owner for your xib implement the extended class. From that point simply add an instance variable to your extended class for the square. The last step in the process is to add methods to your class to bind to each of the controls to actions.

- (IBAction) pinSelected: (id)sender;

Once you create these methods (be sure to make them return IBAction, it is actually an alias for void but acts as a hint to INterface Builder) then you can bind your controls to the method through File's Owner (using control + drag to establish the link).

Good Luck!



回答3:

I found how to do what I needed which is NOT done within the XIB file. It is way simpler than what i thought, eventhough the above suggestions are VALID.

In order to use the square object, I just had to reference the header file:

 #import "square.h"

in the SquareUIViewController.h and add a reference to a square object:

Square *square;

Then in the SquareUIController.m, I just have to allocate/initialize the square object prior doing anything else:

(IBAction)myInit
{
square = [[Square alloc] init];
}

Now I can use the methods of the first post And Voila !

ps: critics, fire up!