Calling instance method from class method: Possible or no?
In a previous post I explained that I was converting an old 'C' program into Objective-C, and learned the difference between messaging (old version) static methods and class methods.
However, how can I now get a class method to call an instance method (assuming it's even possible)? Here's the original (static) function:
static int newSplitB(int b, int hi, int lo, int found)
{
int hlp;
if(hi - lo <= 1)
return 0;
bIs(lo + (hi - lo + 1) / 2); // calls function bIs();
return 1;
}
and the exact same code 'translated'开发者_运维知识库 into Obj-C:
+(int)newSplitB :(int)b :(int)hi :(int)lo :(int)found
{
int hlp;
if((hi - lo) <= 1)
return 0;
[TablesClass bIs:(lo+(hi-lo+1)/2)]; // gives compile error
return 1;
}
The 'bIs()' function -- snipped for brevity -- is sitting in a separate source file in my 'Tables' class. Unfortunately, attempting to build the program gives me a 'TablesClass' undeclared (first use in this function) error, even though the class has been alloc/inited earlier in the same implementation file.
I've searched the net for hours for a solution, but to no avail. If what I'm trying to do isn't possible, how can I modify the last method to do what I'm after? Thanks in advance :-)
Make sure your are importing the TablesClass.h
file otherwise the current class won't know of its existence and is the common issue when dealing with this error.
You said you "alloc/inited" the TableClass earlier in the same implementation file but it seems like you are using it like a static method. You don't have to alloc/init an instance of a class when you want to use its static methods. Also, if you alloc/init at instance of the TableClass, then that means you stored it somewhere that the static method newSplitB could access.
it is possible, and it is not possible, depending on how you view it:
to call an instance method, you need an instance of an object. you can send this message from a class method, if you have an object.
without an instance of the class, you can't call the instance method anywhere.
you may call class methods from anywhere (assuming it's visible in the translation).
if bIS
is just a c function, then there is no need for it to be an instance method. in fact, you could leave it as a c function.
(maybe an extended example would help us understand why this must be an instance method)
精彩评论