2011-11-17 77 views
0

调用某个方法的方式让我非常疯狂!不幸的是我在已经提出的问题中找不到它。 我知道如何分配和初始化 但事情是在我的程序中我需要调用其自己的类内的方法 这里是一个示例实现,当然我知道我可以做到这一点在十几种更简单的方法,但在程序中我开发我有一个非常复杂的案例,我需要这样做调用另一个类的(实例)方法

在我的NIB文件中我有一个标签和两个按钮。 标签和其中一个按钮(称为“设置为今天”)链接在appDelegate 另一个按钮(称为“设置为十天后”)链接到classTwo 这里是所有文件的代码 虽然代码不会产生任何错误,但触发第二个按钮不起作用 什么是调用该方法的正确方法。

AppDelegate.h:

@interface AppDelegate : NSObject <NSApplicationDelegate> 
{ 
    IBOutlet NSTextField *label; 
    NSDate *toDay; 
} 
-(IBAction)setToToday:(id)sender; 
-(void)updateLabelText; 
-(void)setToTenDays; 

@property (assign) IBOutlet NSWindow *window; 
@end 

AppDelegate.m:

#import "AppDelegate.h" 
@implementation AppDelegate 
@synthesize window = _window; 
-(IBAction)setToToday:(id)sender 
{ 
    toDay=[NSDate date]; 
    [self updateLabelText]; 
} 
-(void)updateLabelText 
{ 
    [label setStringValue:[NSString stringWithFormat:@"%@",toDay]]; 
} 
-(void)setToTenDays 
{ 
    int secondsPerDay=60*60*24; 
    toDay = [NSDate dateWithTimeInterval:10*secondsPerDay sinceDate:toDay]; 
} 
@end 

ClassTwo.h

@interface ClassTwo : NSObject 
-(IBAction)setToTenDaysLater:(id)sender; 
@end 

ClassTwo.m

#import "ClassTwo.h" 
#import "AppDelegate.h" 
@implementation ClassTwo 
-(IBAction)setToTenDaysLater:(id)sender 
{ 
    AppDelegate *classOne=[[AppDelegate alloc] init]; 
    [classOne setToTenDays]; 
    [classOne updateLabelText]; 
} 
@end 

为什么我无法将标签设置为新日期? 这两个对象都在NIB文件中,并设置了动作和插座 非常感谢您的帮助。

P.S.以我真实的体验,例如,我在CustomWindow Class中使用触控板事件来更改标签。

回答

3

因为在第二课中,您正在创建AppDelegate的新实例,而不是调用已创建的实例。无论如何,你只应该有一个NSApplicationDelegate。

您需要在头文件中设置ClassTwo对ClassOne的引用,并将它们连接到NIB中,或者以编程方式将其设置,如果您以编程方式创建ClassTwo。

编辑:我已添加属性访问器,请务必阅读declared properties

@class AppDelegate; 

@interface ClassTwo : NSObject { 
    AppDelegate *delegate; 
} 

@property (assign, nonatomic) IBOutlet AppDelegate *delegate; 

- (IBAction)setToTenDaysLater:(id)sender; 

@end 

ClassTwo.m

#import "ClassTwo.h" 
#import "AppDelegate.h" 

@implementation ClassTwo 

@synthesize delegate; 

-(IBAction)setToTenDaysLater:(id)sender { 

    [delegate setToTenDays]; 
    [delegate updateLabelText]; 
} 
@end 

然后在ClassOne(AppDelegate中)你可以只设置delegate属性,像这样:

classTwo.delegate = self; 

classTwo是一个IBOutlet到归档实例中你的XIB,或者你也可以在代码中创建它。

+0

哇!谢谢,这工作!你能帮忙以编程方式设置代表吗? – Nabi

+0

这只是一个将属性添加到ClassTwo实例并在代码中进行设置的问题,我已在上面添加了它。 –

0
DisplayView *year = [[DisplayView alloc] initWithNibName:DisplayView bundle:nil]; 
[self presentModalViewController:year animated:YES];