开发者

How do I Call a method from other Class

开发者 https://www.devze.com 2022-12-25 10:34 出处:网络
I\'m having some trouble figuring out to call methods that I have in other classes #import \"myNewClass.h\"

I'm having some trouble figuring out to call methods that I have in other classes

#import "myNewClass.h"
#import "MainViewController.h"

@implementation MainV开发者_高级运维iewController

@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?


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

精彩评论

暂无评论...
验证码 换一张
取 消