来自另一个类的类方法从未被调用 [英] Class method from another class is never called
问题描述
我试图从另一个类中的一个类调用方法。
@interface示例:NSObject
- (void)displayString:(NSString *)str;
@end
@implementation示例
- (void)displayString:(NSString *)str
{
NSLog(@字符串:%@ ,str);
}
@end
// callExample.h
@interface callExample:UIViewController
@property(nonatomic,strong)example * ex;
@end
//按下此按钮调用函数displayString。
// callExample.m
@implementation callExample
- (IBAction)btnPressed:(id) btn
{
[self.ex displayString:@sampleTEXT];
}
@end
所以当我调试 [self.ex displayString:@sampleTEXT];
,这行代码没有调用示例类中的函数。我想我做的一切正确。我缺少的东西。我在哪里错了?
感谢
首先, displayString
不是类方法,它是一个实例方法。第二个和相关的,你不创建你的示例
类的实例来调用该方法。
让我们把它放在 viewDidLoad
方法 callExample
现在(你不说如果一个实例已经存在) 。像:
self.ex = [[example alloc] init];
此外,请检查命名约定:此处。
I am trying to call method from one class in another class.
@interface example : NSObject
-(void)displayString:(NSString*)str;
@end
@implementation example
-(void)displayString:(NSString*)str
{
NSLog(@"The string:%@",str);
}
@end
// callExample.h
@interface callExample:UIViewController
@property (nonatomic, strong) example *ex;
@end
//the function displayString is called in this button pressed.
// callExample.m
@implementation callExample
- (IBAction)btnPressed:(id)btn
{
[self.ex displayString:@"sampleTEXT"];
}
@end
so when i debug the [self.ex displayString:@"sampleTEXT"];
, this line of code doesnot call the function in example class. I think i am doing everything correctly. i am missing something. where am i going wrong?
any help will be highly appreciated.
Thank
First off, displayString
is not a class method, it's an instance method. Second, and related, you don't create an instance of your example
class to call the method on.
Let's put it in the viewDidLoad
method for callExample
class for now (you don't say if an instance already exists). Something like:
self.ex = [[example alloc] init];
Also, check the naming conventions please: here.
这篇关于来自另一个类的类方法从未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!