我想在Objective C中编写一个类方法。当我声明该方法时,项目生成良好。但是,只要我尝试调用该方法,构建就会失败。这是我的代码。不能调用类方法[self theMethod:]
头文件
#import <UIKit/UIKit.h>
@interface LoginViewController : UIViewController {
//Declare Vars
}
- (IBAction) login: (id) sender;
+ (NSString *) md5Hash:(NSString *)str;
@end
源文件
+ (NSString *) md5Hash:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, strlen(cStr), result);
return [NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (IBAction) login: (id) sender {
//Call the class method
[self md5Hash:@"Test"];
}
真的 - 关键是要拥抱你不编写Java代码。 Objective-C没有静态方法;它有类方法,它们可以被重写,否则就像实例方法一样(类是元类的一个实例)。 – bbum
你应该使用'[[self class] md5Hash]'否则子类将会遇到麻烦,如果他们想从'login:'调用被覆盖的'md5Hash:'。 –