如何从其他类调用方法 [英] How do I Call a method from other Class
问题描述
我很难弄清我在其他班级中遇到的调用方法 b
I'm having some trouble figuring out to call methods that I have in other classes
#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
myNewClass.h
#import <Foundation/Foundation.h>
@interface myNewClass : NSObject {
}
- (NSString*)CalculateSecretForUser:(NSString *)user withPassword:(NSString *)pwd;
@end
myNewClass.m
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方法始终说
the method CalculateSecretForUser always says
'MainViewController'可能不响应'-calculateSecretForUser:withPassword:'
'MainViewController' may not respond to '-calculateSecretForUser:withPassword:'
我在这里做什么错了?
推荐答案
关键字 self表示您的实例当前课程。因此,您正在将消息 calculateSecretForUser:withPassword
发送到 MainViewController
,该消息未实现。您应该实例化 myNewClass
并调用它:
The keyword "self" means the instance of your current class. So you are sending the message calculateSecretForUser:withPassword
to MainViewController
which does not implements it. You should instantiate myNewClass
and call it :
- (IBAction)calculateSecret {
myNewClass *calculator = [[myNewClass alloc] init];
NSString *usec = [calculator calculateSecretForUser:txtUsername.text
withPassword:txtPassword.text];
[lblUserMessage setText:usec];
[usec release];
[calculator release];
}
这篇关于如何从其他类调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!