我有 2 个班级,比如 A 班和 B 班.B 类是在 A 类中创建的.我在A类中有一个方法,需要在A类和B类中都执行.在A类中调用方法本身就可以了.但我不确定在 B 类中调用该方法.我尝试将方法声明为静态,但由于我不能在静态方法中使用实例变量,我认为使用委托是个好主意.由于我来自 C# 背景,我不确定在 Objective C 中使用它.从概念上讲,我已经在 C# 中实现了我需要的东西,如下所示.只是想知道它在 Objective C 中的等价物.
I have 2 classes, say class A and class B. Class B is created in class A. I have a method in class A, which needs to be executed in both class A and class B. Calling the method in class A itself is fine. But I am not sure about calling the method in class B. I have tried declaring the method as static, but since I can't use instance variables inside the static method, I think using delegates would be a good idea. Since I am from a C# background, I am not sure about using it in Objective C. Conceptually, I have implemented what I need in C# as shown below. Just wanted to know what the equivalent of it would be in Objective C.
class A
{
public A()
{
B myclass = new B(() => calculate());
}
public void calculate()
{
// todo
}
}
class B
{
public B(Action calculate)
{
calculate();
}
}
是否可以使用协议来做到这一点.
Is it possible to do this using protocols.
刚好在研究的时候看到这个帖子.这是一个示例代码:
I just happened to see this post while researching. Here is a sample code:
ClassA.h 文件:
ClassA.h file:
#import <Foundation/Foundation.h>
#import "ClassB.h"
@interface ClassA : NSObject <ClassBDelegate>
@end
ClassA.m 文件:
ClassA.m file:
#import "ClassA.h"
@implementation ClassA
-(void)createAnInstanceOfClassB
{
ClassB *myClassB = [[ClassB alloc]init]; //create an instance of ClassB
myClassB.delegate = self; //set self as the delegate
// [myClassB optionalClassBMethod]; //this is optional to your question. If you also want ClassA to call method from ClassB
}
-(void)calculate
{
NSLog(@"Do calculate thing!"); // calculate can be called from ClassB or ClassA
}
@end
ClassB.h 文件:
ClassB.h file:
#import <Foundation/Foundation.h>
@protocol ClassBDelegate <NSObject>
-(void)calculate; //method from ClassA
@end
@interface ClassB : NSObject
@property (assign) id <ClassBDelegate> delegate;
//-(void)optionalClassBMethod; //this is optional to your question. If you also want ClassA to call method from ClassB
@end
ClassB.m 文件:
ClassB.m file:
#import "ClassB.h"
@implementation ClassB
@synthesize delegate;
-(void)whateverMethod
{
[self.delegate calculate]; // calling method "calculate" on ClassA
}
//-(void)optionalClassBMethod //this is optional to your question. If you also want ClassA to call method from ClassB
//{
// NSLog(@"optionalClassBMethod");
// [self whateverMethod];
/