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'm pretty sure what you are looking for is blocks.
In class A, you can define calculate() as a block.
Then in class B, you could have some kind of method that took in a block for calculation and returned some new instance of B based on the calculation (I'm assuming that is what was intended?).
I just happened to see this post while researching. Here is a sample code:
ClassA.h file:
ClassA.m file:
ClassB.h file:
ClassB.m file:
You could make one class a delegate of the other but that is kind of arbitrary relationship-wise.
Is there any reason not to use inheritance - both A + B subclass from Z - and Z is where your common method is? Then they could both call
[self calculate];
you can do this using notificationCenter. e.g
Class A .h
.m
when you call the method in ClassB:
What you are looking is possible with Objective C.
You can refer this post. But for that you have to learn some syntax of Objective C.
If you are not familiar with Objective C & not direct deal with Cocoa frame work then you can do your work using Objective C++. Where you can write your code in C++.
Here you can use function pointer & pass static method of class A.
Or you can define interface class. Derive class A from that & pass object of A to class B.