如何从另一个类调用方法

时间:2010-04-05 07:33:28

标签: objective-c call

我在其他类

中找出调用方法时遇到了一些麻烦
#import "myNewClass.h"
#import "MainViewController.h"

@implementation MainViewController

@synthesize txtUsername;
@synthesize txtPassword;
@synthesize lblUserMessage;

- (IBAction)calculateSecret {

NSString *usec = [self calculateSecretForUser:txtUsername.text 
                       withPassword:txtPassword.text]; 

    [lblUserMessage setText:usec];
    [usec release];
} 
...

myNewClass.h

#import <Foundation/Foundation.h>

@interface myNewClass : NSObject {
}
- (NSString*)CalculateSecretForUser:(NSString *)user withPassword:(NSString *)pwd;

@end

myNewClass.m

#import "myNewClass.h"

@implementation myNewClass

- (NSString*)CalculateSecretForUser:(NSString *)user withPassword:(NSString *)pwd
{
    NSString *a = [[NSString alloc] initWithFormat:@"%@ -> %@", user, pwd]; 
    return a;
}

@end

方法CalculateSecretForUser总是说

  

'MainViewController'可能无法响应'-calculateSecretForUser:withPassword:'

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

关键字“self”表示当前类的实例。因此,您要将calculateSecretForUser:withPassword发送给MainViewController,但不会实现该消息。您应该实例化myNewClass并将其命名为:

- (IBAction)calculateSecret {
    myNewClass *calculator = [[myNewClass alloc] init];

    NSString *usec = [calculator calculateSecretForUser:txtUsername.text 
                        withPassword:txtPassword.text]; 

    [lblUserMessage setText:usec];
    [usec release];
    [calculator release];
}