【问题标题】:Objective-C - Call a method that modify a textField from another classObjective-C - 调用从另一个类修改文本字段的方法
【发布时间】:2016-03-26 20:26:14
【问题描述】:

我有两个问题:

    1234563 当我通过 (IBAction)internet 方法执行此操作时,它可以工作.. 有什么解决方案吗?
  • 为什么 Xcode 要我在变量(如 internetTextfield)之前加上 _ 来调用它?

WindowsController.h

#import <Cocoa/Cocoa.h>

@interface WindowController : NSWindowController
@property (assign) IBOutlet NSTextField *internetLabel;

- (void)statutInternet;
- (IBAction)internet:(id)sender;

@end

WindowsController.m:

#import "WindowController.h"
@implementation WindowController

- (IBAction)internet:(id)sender;
{
   [self statutInternet];
}

- (void)statutInternet;
{
    NSLog(@"Callfunctionworks");
    if (condition) {
    [_internetLabel setStringValue:@"TxtFieldWorks!"];
    }

}

我尝试从另一个类中调用 statutInternet 方法:

WindowController *fenetre = [[WindowController alloc] init];
[fenetre statutInternet];

【问题讨论】:

    标签: objective-c methods nstextfield


    【解决方案1】:

    当我尝试调用不同类的方法时,它不起作用:

    那是因为,您正在使用此代码创建另一个 WindowController 实例:

    WindowController *fenetre = [[WindowController alloc] init];
    

    这是同一个类的另一个新的单独实例,我猜你没有显示。因此,您希望参考已经显示的窗口,而不是创建一个新实例。

    为什么 Xcode 要我在变量(如 internetTextfield)之前加上 _ 来调用它?

    那是因为当您使用 @property 声明变量时,它会做三件事:

    1. 通过将常规下划线 (_) 添加到变量名称的开头来创建内部变量。这就是您将 _ 作为变量前缀的原因。
    2. 创建一个 setter-getter 方法。
    3. 在实施 setter-getter 时考虑您使用的关键字(即assign、strong、weak)。

    你可以在这里阅读一个很好的讨论:@property and retain, assign, copy, nonatomic in Objective-C

    【讨论】:

    • 好的,谢谢,我不知道..如何在不创建新实例的情况下调用现有实例?
    • 实际上你需要知道你在你的应用程序中首先创建这个实例的位置,可能是你的应用程序委托?
    • 是的,我认为,(我从现有项目开始:ASHStatusItemPopover github.com/adamhartford/ASHStatusItemPopover)这是我在 AppDelegate 中的内容:ASHStatusItemPopover *statusItemPopover = [[ASHStatusItemPopover alloc] init]; statusItemPopover.windowController = [[WindowController alloc] initWithWindowNibName:@"WindowController"];
    • 你需要在你的其他班级有这个参考。
    【解决方案2】:

    调用 statutInternet 方法时,NSTextField(以及所有其他 UI 项)尚未创建。

    当你的窗口加载后,你的视图就准备好了:

    _fenetre = [[WindowController alloc] initWithWindowNibName:@"WindowController"];
    [_fenetre showWindow:_fenetre.window];
    [_fenetre statutInternet];
    

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2013-03-05
      • 2017-08-02
      • 2015-08-01
      • 1970-01-01
      相关资源
      最近更新 更多