objective-c – 目标c访问公共方法

objective-c – 目标c访问公共方法,第1张

概述我尝试从另一个类访问公共方法.我已经尝试了很多我在网络上找到的例子,但它们并没有按照我希望的方式工作. Class1.h @interface anything : NSObject { IBOutlet NSTextField *label;}+ (void) setLabel:(NSString *)string;- (void) changeLabel:(NSString 我尝试从另一个类访问公共方法.我已经尝试了很多我在网络上找到的例子,但它们并没有按照我希望的方式工作.

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"];}

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

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

自定义类

@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

类和对象方法

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

总结

以上是内存溢出为你收集整理的objective-c – 目标c访问公共方法全部内容,希望文章能够帮你解决objective-c – 目标c访问公共方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1008281.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存