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!
Here a short example for what you can do:
The Custom Class
Using it
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 propertiesobjectOfYourCustomClass.title = @"something". Then you can call[objectOfYourCustomClass doSomethingWithTheTitle];, which is a public object method.