Update UI from another Class Method - Cocoa

前端 未结 3 996
清歌不尽
清歌不尽 2021-01-14 14:09

I would like to update the UI in my application from the AppDelegate, but whenever I call it as so:

Controller *object = [[Controller alloc] init];
[object          


        
3条回答
  •  轮回少年
    2021-01-14 14:51

    This is really simple, and Chuck's comments basically explain what you need to do, but I will lay out the code explicitly for you. In testAppDelegate.h:

    @interface testAppDelegate : NSObject  {
        NSWindow *window;
        // You can make an IBOutlet to any kind of object you
        // want; it's just a way for you to get a reference
        // in code to an object that has been alloc'd and
        // init'd already by the xib mechanism.
        IBOutlet Controller *controller;
    
    }
    

    Then go into your xib in InterfaceBuilder and hook up that outlet from your Test App Delegate object to your Controller object (these objects are already present in the xib).

    In testAppDelegate.m:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        // This is the key:
        // _Don't_ alloc/init a new controller object. The 
        // objects in your xib are allocated and initialized 
        // by virtue of being in that file. You just need to 
        // give your AppDelegate a pointer to it, as above.
        [controller setTextValue:@"hello"];
    }
    

提交回复
热议问题