目标c访问公共方法

Vin*_*ich 7 cocoa objective-c nstextfield public-method

我尝试从另一个类访问公共方法.我已经尝试了很多我在网络上找到的例子,但它们并没有按照我希望的方式工作.

Class1.h

@interface anything : NSObject {

    IBOutlet NSTextField *label;

}

+ (void) setLabel:(NSString *)string;
- (void) changeLabel:(NSString *)string2;
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

Class2.m

- (IBAction)buttonPressed {

    [Class1 setLabel:@"Test"];

}
Run Code Online (Sandbox Code Playgroud)

非常奇怪的是,在NSLogs中,一切都很好,在两个NSLog中,字符串都是"Test",但textField的stringValue不会改变!

Inf*_*ite 13

-+不是指公共或私人

- 代表你可以调用类和对象的方法

+ 代表可以在类本身上调用的方法.

  • 换句话说,`+`表示静态,`-`表示非静态 (8认同)
  • 很好的答案,虽然技术上这些是*方法*,而不是功能. (3认同)

NSA*_*ict 8

这是一个简短的例子,说明你可以做什么:


自定义类

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

- (void)doSomethingWithTheTitle;
@end

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

使用它

@implementation ITAppDelegate

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

@end
Run Code Online (Sandbox Code Playgroud)

类和对象方法

使用+表示方法,可以直接在类上调用方法.就像你用它做的那样[myClass1 setLabel:@"something"];.这没有意义.你想要的是创造一个财产.属性保存在对象中,因此您可以创建对象ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init];并设置属性objectOfYourCustomClass.title = @"something".然后你可以调用[objectOfYourCustomClass doSomethingWithTheTitle];,这是一个公共对象方法.