Question

I try to access a public method from another class. I already tried many examples I found in the web, but they didn't work in the way I wanted them to.

Class1.h

@interface anything : NSObject {

    IBOutlet NSTextField *label;

}

+ (void) setLabel:(NSString *)string;
- (void) changeLabel:(NSString *)string2;

Class1.m

+ (void) setLabel:(NSString *)string {

    Class1 *myClass1 = [[Class1 alloc] init];

    [myClass1 changeLabel:string];
    NSLog(@"setLabel called with string: %@", string);

}

- (void) changeLabel:(NSString *)string2 {

    [label setStringValue:string2];
    NSLog(@"changeLabel called with string: %@", string2);
}

Class2.m

- (IBAction)buttonPressed {

    [Class1 setLabel:@"Test"];

}

Very strange is that in the NSLogs, everything is fine, in both NSLogs, the string is "Test", but the textField's stringValue doesn't change!

Was it helpful?

Solution 2

Here a short example for what you can do:


The Custom Class

@interface ITYourCustomClass : NSObject
@property (strong) NSString *title;

- (void)doSomethingWithTheTitle;
@end

@implementation ITYourCustomClass
- (void)doSomethingWithTheTitle {
    NSLog(@"Here's my title: %@", self.title);
}
@end

Using it

@implementation ITAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init];
    [objectOfYourCustomClass doSomethingWithTheTitle];
}

@end

Class and object methods

Declaring a method with + means, that you can call the method directly on a class. Like you did it with [myClass1 setLabel:@"something"];. This doesn't make sense. What you want, is creating a property. A property is saved in an object, so you can create an object ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init]; and setting the properties objectOfYourCustomClass.title = @"something". Then you can call [objectOfYourCustomClass doSomethingWithTheTitle];, which is a public object method.

OTHER TIPS

- and + don't mean public or private

- stands for methods that you can call on objects of the class and

+ stands for methods that can be called on the class itself.

You're trying to access an instance variable with a class method. You should convert the +setLabel: method to -setLabel:, and call it like this:

[_myClass1Variable setLabel:@"Test"];

Additionally, what's -setStringValue? If you're just trying to change the text of the UILabel you need to call -setText:.

I guess label would be a NSTextField, and you are tring to set its value without loading that XIB, resulting that your awakeFromNib is not getting called. And the outlet will not be bound that that label.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top