It's very simple to create a new object without using alloc
from Foundation. The Objective-C runtime library itself provides functions that allow one to allocate objects from classes and deallocate them later, so that you need no extra library to create and destruct objects.
The function id class_createInstance(Class cls, size_t extraBytes)
receives a class object, from which to allocate a new object, and an integer, which is almost always zero, and returns a new instance of cls
.
Similarly, the function id object_dispose(id obj)
takes an Objective-C object, calls the C++ destructor of every C++ object instance variable, removes existing associated references and frees it.
class_createInstance
and object_dispose
are both declared in /usr/include/objc/runtime.h
.
So, you can implement your own +alloc
and -dealloc
methods. Your program would look like this:
#include <stdio.h>
#include <objc/runtime.h>
@interface Foo{
char * bar;
}
+(id)alloc;
-(void)hello;
@end
@implementation Foo
+(id)alloc {
// Returns a new 'Foo' object. In this case, 'self' is a 'Foo' class object,
// whose type is 'Class', as required by `class_createInstance`.
return class_createInstance(self, 0);
}
-(void)dealloc {
object_dispose(self);
}
-(void)hello {
printf("Hello world!");
}
@end
int main(){
Foo *foo = [Foo alloc];
[foo hello];
[foo dealloc];
return 0;
}
Compile it as you normally do:
gcc Foo.m -o Foo -lobjc
That's all!