Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c accessing public method

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!

like image 740
Vincent Friedrich Avatar asked Dec 21 '12 12:12

Vincent Friedrich


2 Answers

- 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.

like image 67
Infinite Avatar answered Sep 22 '22 00:09

Infinite


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.

like image 41
IluTov Avatar answered Sep 24 '22 00:09

IluTov