Access IBOutlet from other class (ObjC)

妖精的绣舞 提交于 2019-11-27 07:24:52

问题


I've googled around and found some answers but I didn't get any of them to work. I have one NSObject with the class "A" and a second class "B" without an NSObject. In class "A" are my IBOutlets defined and I can't seem to figure out how to access those outlets from class "B"...

I've found answered questions like http://forums.macrumors.com/archive/index.php/t-662717.html But they're confusing.

Any help would be greatly appreciated!

Simplified Version of the Code:

aClass.h:

#import <Cocoa/Cocoa.h>

@interface aClass : NSObject {
    IBOutlet NSTextField *textField;
}
@end


aClass.m:

#import "aClass.h"

@implementation aClass
// Code doesn't matter
@end


bClass.h:

#import <Cocoa/Cocoa.h>

@interface bClass : NSObject {
}
@end


bClass.m:

#import "aClass.h"
#import "bClass.h"

@implementation bClass
    [textField setStringValue: @"foo"];
@end

回答1:


When you write:

I have one NSObject with the class "A" and a second class "B" without an NSObject.

It tells me that you don't have your head around the basic concepts. Read through Apple's objective-C introduction, and the tutorial projects.




回答2:


The solution is using NSNotificationCenter. Here's a thread telling you how to do it: Send and receive messages through NSNotificationCenter in Objective-C?

Then in the method reacting to the notification, you call a method accessing the Outlet

- (void) receiveTestNotification:(NSNotification *) notification
{

    if ([[notification name] isEqualToString:@"TestNotification"])
        //NSLog (@"Successfully received the test notification!");
        [self performSelectorOnMainThread:@selector(doIt:) withObject:nil waitUntilDone:false];
}
- (void) doIt
{
    //testLabel.text = @"muhaha";
}

This worked for me, I hope it does so for you as well.



来源:https://stackoverflow.com/questions/1936185/access-iboutlet-from-other-class-objc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!