How do I Call a method from other Class

不问归期 提交于 2019-12-25 03:03:25

问题


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

#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

the method CalculateSecretForUser always says

'MainViewController' may not respond to '-calculateSecretForUser:withPassword:'

what am I doing wrong here?


回答1:


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


来源:https://stackoverflow.com/questions/2577366/how-do-i-call-a-method-from-other-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!