I know that you can declare a C function outside of a class, but is it possible to declare a Objective-C method outside of a class?
Example:
// Works
void printHelloC()
{
NSLog(@"Hello.");
}
// Error
-(void) printHelloOC
{
NSLog(@"Hello.");
}
int main (int argc, const char * argv[])
{
@autoreleasepool {
printHelloC();
[self printHelloOC];// 'self' obviously would not work but you get the idea
}
return 0;
}
The definitions of class methods can be anywhere outside of the class. When you define a class method outside the class, you need to prefix the method name with the class name and scope resolution operator. The important part is not to use the scope access keywords, such as private , protected or public .
No its not possible. In java everything (objects) belongs to some class. So we can not declare function(method) outside a class.
You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.
It depends. You can do something similar with method adding at runtime:
#import <objc/runtime.h>
void myCustomMethod(id self, SEL _cmd, id arg1, id arg2)
{
NSLog(@"This is a test, arg1: %@, arg2: %@", arg1, arg2);
}
int main(int argc, char *argv[])
{
Class NSObjClass = [NSObject class];
class_addMethod(NSObjClass, @selector(myNewMethod::), (IMP) myCustomMethod, "v@:@@");
NSObject myObject = [NSObject new];
[myObject myNewMethod:@"Hi" :@"There"];
[myObject release];
return 0;
}
But that is about it outside of a @class construct, and it really just covers up what happens with a category.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With