How to instantiate a control in code instead of using Interface Builder ?

I really appreciate the combination of the interface builder and Xcode altogether.
However when I am learning QT, I realize I had been pampered by Apple's Design to a certain extend as I only need to create say a NSLabel instance and use Interface Builder to do the linking and never have to worry about instantiating the Object myself.
But I'm curious, what is the way to instantiate a new hmmm say...NSLabel in the code ?
NSLabel* label = new NSLabel();
Then what ?
What you are seeing here is how QT did it, could anyone create an equivalent in ObjC ? No fancy code please, just bare minimum.
#include <QApplication>
#include <QWidget>
#include <QLabel>
int main (int argc, char * argv [ ])
QApplication app(argc, argv); //NSApplication in ObjC
//These two lines merely created a window and set the title bar text.
QWidget* window = new QWidget();
window->setWindowTitle("Hello World");
QLabel* label = new QLabel(window);//Create a label and inform the it belongs to window.
label->setText("Hello World");
window->show();
return app.exec();
Message was edited by: Bracer Jack

Hi Jack -
I think my best answer will be something of a disappointment, because I don't know how to show a one-to-one correspondence between the code you're working with and a Cocoa program. The main function of a Cocoa GUI program for OS X will look something like this:
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
return NSApplicationMain(argc, (const char **) argv);
As you commented, we could draw a correspondence between the first statements, but after that the functionality of the Cocoa program is going to be spread out in a way that makes for a rather tedious comparison. The only way I know to answer your question in less than 5000 words, is to skip ahead to one of several points in the startup sequence where the programmer can intervene with custom code.
For example, a common way to get control would be to program a custom controller class and add an object of that class to the main nib file which is loaded during the startup sequence. By making a connection to the Application object in that nib file, the custom object could be made the delegate of the Application object, and if we then added a method named applicationDidFinishLaunching, our code would run as soon as the application's run loop was started.
Now I finally have enough context to directly answer your question, so here is the code to create a label and add it to the key window at launch time:
// MyAppController.m
#import "AppController.h"
@implementation AppController
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSLog(@"applicationDidFinishLaunching");
NSRect frameRect = NSMakeRect(150, 300, 150, 30);
NSTextField *label = [[NSTextField alloc] initWithFrame:frameRect];
[label setEditable:NO];
[label setStringValue:@"Hello World!"];
[label setFont:[NSFont labelFontOfSize:20]];
[label setAlignment:NSCenterTextAlignment];
NSView *contentView = [self.window contentView];
[contentView addSubview:label];
@end
If I needed to develop a worst case scenario for this thread, the next question would be, "Ok sure, but your code still needs a nib to start up. I want to see a Cocoa GUI program that doesn't require any nib".
It turns out that it's quite easy to build a simple iPhone app without any nib, but it's considerably more difficult for an OS X app. If anyone wants to see my nib-less iPhone code, I'll be happy to post it (I think I did post it here once before, and the response was underwhelming). But I've never attempted the much more difficult nib-less OS X app. Just in case you really want to go there, here's a blog that goes into the details: [http://lapcatsoftware.com/blog/2007/07/10/working-without-a-nib-part-5-open-re cent-menu>.
Hope some of the above is helpful!
- Ray

Similar Messages

  • How to find a control with code

    I could find the control with the Test Builder, but now, what I want is achieve that by code. How could I define what the property
    to search? Any help would be appreciated.

    Hi mokpoju,
    Generally, I know that if we want to find a control by code, we will need to add the searchproperties or filterproperties to find this control in the UIMap.Designer.cs file.
    For example, you could use this searchproperties or filterproperties to find the control's ID, Name properties etc.
    For more information, please refer this following blog to check your issue.
    http://blogs.msdn.com/b/balagans/archive/2009/12/28/9941582.aspx
    http://blogs.msdn.com/b/mathew_aniyan/archive/2009/02/12/hand-coding-a-coded-ui-test.aspx
    Hope it help you!
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How can i tell if Native code is being used or not?

    Hi,
    I imported a jar file called dnsjava, and set my system property to use this so that my getHostName method doesnt use native code to get the host name. My question is, how can i know for sure that it is using the code from the jar file dnsjava? I used a debugger, and it seemed like it was getting it from java.net.InetAddress instead. Please help!
    import java.net.InetAddress;
    public class Test {
         public static void main(String[] args) throws Exception {
              System.setProperty("sun.net.spi.nameservice.provider.1","dns,dnsjava");
              InetAddress addr = InetAddress.getByName("64.58.76.179");
              String name = addr.getHostName();
              System.out.println("name = " + name);
    }

    What makes you think that you can set that property in the code and it will work?
    A number of properties can only be set from the command line. They will not work when set in code.
    I am not sure that any sun type properties will work when set in code.

  • How can I purchase a redemption code for a used Premiere Elements 11?

    My wife bought me a used version of Adobe Premiere Elements 11.  When I try to enter the redemption code, it says that the code is not valid.  How can I purchase another redemption code / serial number?  Thanks!

    When I went to Best Buy online and searched for Premiere Elements 11 a page came up that shows that program being sold by "marketplace" vendors
    http://www.bestbuy.com/site/searchpage.jsp?_dyncharset=UTF-8&_dynSessConf=1374273800958887 553&id=pcat17071&type=page&ks=960&st=premiere+elements&sc=Global&cp=1&sp=&qp=soldby_facet% 3DSAAS%7ESold+By%7EMarketplace+Seller&list=y&usc=All+Categories&nrp=15&fs=saas&iht=n&seeAl l=
    I did not click through to go to any of the vendors, so I don't know if any of them actually sell USED software

  • How do I create accessible Mobile APP for IPAD using flash Builder 4.7?

    How do I create Accessible Mobile App for IPAD usign Flash Builder 4.7?
    I tried updating enabling accessbile = True and other configuratoin from this site: http://www.adobe.com/accessibility/products/flex/best-practices.html
    but NO LUCK. When I tested on IPAD it freezes my App.
    Thanks for your time and help,
    Nim Pat

    In the second example, the photo is set to background with a tile. The other parts are over top of the photo and done with layers with a background color setting.

  • How can I get the ASCII code instead of Unicode?

    If I use getNumericValue to return the Unicode of a character, I found out "a" = "A". Is there any way I can find out the different code for capital letter and small letter? I'm thinking about ASCII code, any suggestion for which method to return the ASCII code?

    That is not what getNumericValue does. (Try getNumericValue('*'), for example, and you will see it returns -1.) If you want to find the Unicode value of a character, simply cast the character to an int:char letter = 'A';
    int unicodeValue = (int)letter;If the character you chose was in the ASCII character set, you will automatically have its ASCII code, because ASCII is simply the first 128 characters in the Unicode character set.

  • Spry slideshow - how can i remove the title code when i use the widget??

    When I insert the slideshow widget, there is code for a title. I don't need this and don't want to have to remove the code each time I use the widget.
    Where can I change this permanently?
    <ul id="ImageSlideShow" title="Bookcase03091-1">
                    <li><a href="/aphoto1/mar9/bookcase-1a.jpg" title="White Orchids">
    I want to remove title information. I looked through all the JS pages and couldn't find the place to do this. Othewise the slideshow works great. I am using Dreamweaver CS5.
    Thanks for helping me!

    Gramps thanks for getting back to me. I went to the Widget Browser, opened the slideshow with film strip and clicked on configure.
    I Disabled the sliding titles and made the main title blank. Then I saved the preset.
    Unfortunately it didn't work. I tried three times. The sliding titles still appear.
    Please try it and see if you can get it to work- thank you!

  • How To Fade In a JPG or GIF Image using Inspector Build-In or Action

    Inspector doesn't seem to have any Build-In or Action that allows me to FADE IN an image.
    There only seems to be an Opacity Action that allows a FADE OUT.
    This seems like kind of a software design oversight. Am I missing something in Keynote?

    The Dissolve transition can be used for either/both a fade-in or a fade-out.
    ... but by now you already know that.
    Message was edited by: Brie Fly

  • How to add third party dll in our installer using application builder?

    Hello friends,
    I have one application (VI) which is using some third party dll of protocol and now I want to make a installer which should install dll along with application exe. Please suggest the way ..
    Thanks
    Solved!
    Go to Solution.

    Hi,
    I placed it in project file and included it in category of "Always Included" in exe creation. Then after i created installer with needed NI drivers. But this installer didn't registered the dlls in project file. I registered it manually using regsvr32 command..
    Any help to do it automatically during installation..
    To brief my words, I need help to understand the process of third party dll registration during installation of installer created by application builder..
    Thanks

  • How to display plant code instead plant description?

    Hi,
    In tx ME21N, ME22N and ME23N, how can I display the plant code instead the plant description?
    Thanks in advance.

    Hi,
    Click the personal setting push button.  There click the display key check box.  Then try.
    Regards,

  • Set my own key instead of using KeyGenerator.generateKey() - how?

    How can I set my own key instead of using KeyGenerator.generateKey()?
    I don´t see any method that is alowing this.

    I have now tried my own.
    To send encrypted data through a CipherOutputStream, I have done this:
    private File file;
            private CipherOutputStream cos;
            private Cipher cipher;
            private PBEKeySpec key;
            private char[] password = "test".toCharArray();
            public SendFileThread(File file)
                this.file = file;
                try
                    key = new PBEKeySpec(password);
                    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                    SecretKey pbeKey = factory.generateSecret(key);
                    cipher = Cipher.getInstance("PBEWithMD5AndDES");
                    cipher.init(Cipher.ENCRYPT_MODE, pbeKey);
                catch(Exception err) {err.printStackTrace();}
            public void run()
                byte [] mybytearray  = new byte [(int)file.length()];
                try
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    OutputStream os = socket.getOutputStream();
                    cos = new CipherOutputStream(os, cipher);
                    int byteCount = 0;
                    int length = mybytearray.length;
                    while(byteCount < mybytearray.length)
                        cos.write(mybytearray[byteCount]);
                    os.flush();
                    os.close();
                    socket.close();
                catch(FileNotFoundException err){err.printStackTrace();}
                catch(IOException err){err.printStackTrace();}To receive the encrypted data and then decrypt it, I use the same password and Cipher.DECRYPT_MODE in the Cipher.init() method.
    private Socket sock;
            private DataInputStream din;
            private CipherInputStream cin;
            private BufferedOutputStream out_file;
            private Cipher cipher;
            private PBEKeySpec key;
            private char[] password = "test".toCharArray();
            public ListenForConnectionThread()
                try
                    key = new PBEKeySpec(password);
                    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
                    SecretKey pbeKey = factory.generateSecret(key);
                    cipher = Cipher.getInstance("PBEWithMD5AndDES");
                    cipher.init(Cipher.DECRYPT_MODE, pbeKey);
                catch(Exception err) {err.printStackTrace();}
            public void run()
                try
                    serverSocket = new ServerSocket(2000);
                    sock = serverSocket.accept();
                    Runnable r = new Runnable()
                        public void run()
                            try
                                cin = new CipherInputStream(sock.getInputStream(), cipher);
                                out_file = new BufferedOutputStream(new FileOutputStream("received_file.txt"));
                                int inputLine;
                                while((inputLine = cin.read()) != -1)
                                    out_file.write(inputLine);
                                out_file.flush();
                            catch(Exception err){err.printStackTrace();}When I run the application, I get this error:
    java.security.InvalidKeyException: requires PBE parameters.
    Why?

  • How to stop reuse asset code once its use in po

    Dear All,
    how to stop reuse of asset code once its use in PO or PR.
    Thanks & Regards,
    Mukesh Chejara
    SAP

    Dear All,
    Awaiting your valuable reply.
    Thanks & Regards,
    Mukesh Chejara
    SAP

  • How do you make a tool bar on interface builder

    I don't know how to make a toolbar (for example: like the one safari) using interface builder.

    Might start here:
    http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptua l/MobileHIG/SystemProvided/SystemProvided.html
    In IB, you'll want to look over the objects in the libary pane/window. These are drag/drop into whatever view you're working, etc. Wiring them up of course depends on usage.
    Apple's 'UICatalog' is another good reference that you can get your hands into and push around for protos and ideas.

  • How can i use the project code instead of project xml?

    hello
    i use the sessionbean+toplink structure,after i finish the o-r mapping by using the mapping work bench,i generate the project xml file,then in the "session.xml" file,i refer to the project xml,then i can use it from sessionbean.
    i hear that if i use the project code instead of project xml file,it will be more performant,is that true?
    otherwise,how can i use the project code instead of project xml file?i mean, in "session.xml", i can use the "<project-xml>" tag to refer to the project xml file,then in my session bean,i get the server session by read the "session.xml" file.but if i use the project code,how can i refer it from the "session.xml"?the examples that come with the toplink installation only tell me how can i use the project xml file within the session bean,it don't give me any clue about using the project code in the sesion bean,who can give me a step-by-step instruction and code snippet?
    thank you very much?

    There is a slight performance gain during session load at startup but there is no difference at runtime. The choice of which to use is dependent upon you build process. Whether it is easier to submit a new version of the class into the comile build process vs an XML file. In most cases it is just a preference of the development team.
    When you use the project-class you'll need to generate the source code and compile it into your system. Typically it is packaged with the persistent classes. You may need to configure your environment so that the class-loaders have access to these classes (same for the XML case).
    When using the project-class you simply replace the project-xml entry like this:
    <project-class>oracle.toplink.demos.employee.relational.EmployeeProject</project-class>
    The DTD for the session.xml file is found at <TOPLINK_HOME>\core\sessions_4_5.dtd. It is also in the documentation at:
    http://otn.oracle.com/docs/products/ias/doc_library/90200doc_otn/toplink.903/b10064/a-sessio.htm#634246
    Doug Clarke
    Product Manager
    Oracle9iAS TopLink

  • Printer is asking for an user acces code instead of windows login and password?

    I have been seeing the HP printers asking(LaserJet M4555 MFP, LaserJet 500 color MFP M575 etc) for user access code instead of windows login and password.
    One thing i have noticed  is that when this happens there is a slight change in the EWS page configuration at security -> access control.The device administrator tabe is unchecked as you can see below ehen this happens
    Have tried cold resetting the printer and restore facory settings but this does not works and some thimes it does works for a while but the issue is returing back.
    We do not need this access code promt instead we need the usual windows login and password that used be there originally.
    alsothis is how the settings look like after a cold reset somtimes when it does not  asks for user access code , the problem is cold rese does lways works and it reverts back ois original settings

    @munish259272 
    ‎Thank you for using HP Support Forum. I have brought your issue to the appropriate team within HP. They will likely request information from you in order to look up your case details or product serial number. Please look for a private message from an identified HP contact. Additionally, keep in mind not to publicly post ( serial numbers and case details).
    If you are unfamiliar with the Forum's private messaging please click here to learn more.
    Thank you,
    Omar
    I Work for HP

Maybe you are looking for

  • Mac running slow when cut and paste

    Hi, recently I noticed that my mac is running slow when I cut and paste (there is a delay of approx 1-2 secs). I thought it might be some kind of spyware which is trying to steal sensitive information such as passwords, credit cards and others. That

  • Is it possible to preserve creation/mod dates when transfering Mac-PC-Mac?

    Hi there I tried researching the following problem on-line but couldn't find anything helpful so was hoping someone else might know something helpful. Historically I have always used PCs so until last year I didn't own a Mac, although I use them at w

  • SDK 3.0 - CDC for Windows Mobile

    Hi, Where can I found the file .cab for install the CDC JVM of SDK 3.0 in my Windows Mobile? Now, I use the Creme JVM for developer in Windows Mobile, but I want use the new SDK 3.0, more specific the CDC JVM in my WM application I see that in path (

  • Help! How do I lengthen a still image that has another still image in front of it?

    When I try to lengthen the first of two adjacent still images in a single video track, I cannot do so. I can shorten the image, and I can both lengthen and shorten the duration of the second image, but that's all. I assume there is a very easy settin

  • Want to trigger at selection screen on 'X'  using mouse click event.

    I've designed a report which has two radiobuttons i would to like change the selection screen depends on the selection of the button as of now i'm selecting the button and hitting enter so that at selection screen on radiobutton group triggers.but fo