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!
-
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.
Here a short example for what you can do:
@interface ITYourCustomClass : NSObject
@property (strong) NSString *title;
- (void)doSomethingWithTheTitle;
@end
@implementation ITYourCustomClass
- (void)doSomethingWithTheTitle {
NSLog(@"Here's my title: %@", self.title);
}
@end
@implementation ITAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init];
[objectOfYourCustomClass doSomethingWithTheTitle];
}
@end
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With