Given this:
Person.h:
@interface Person
{
}
- (void) sayHello;
@end
Person.m:
#import "Person.h"
@implementation Person
- (void)sayHello
{
printf("%s", "Steve");
}
@end
How do you instantiate the Person? I tried this:
Person *p = [Person new];
That doesn't work, nor this:
Person *p = [Person alloc];
[UPDATE]
I forgot to tell, I already tried inheriting from NSObject, the new and alloc works. I'm just curious if we can instantiate a class that doesn't inherit from NSObject?
You absolutely can do so. Your class simply needs to implement +alloc
itself, the way that NSObject
does. At base, this just means using malloc()
to grab a chunk of memory big enough to fit the structure defining an instance of your class.
Reference-counted memory management would also be nice (retain
/release
); this is actually part of the NSObject
protocol. You can adopt the protocol and implement these methods too.
For reference, you can look at the Object
class, which is a root ObjC class like NSObject
, that Apple provides in its open source repository for the Objective-C runtime:
@implementation Object
// Snip...
+ alloc
{
return (*_zoneAlloc)((Class)self, 0, malloc_default_zone());
}
// ...
- init
{
return self;
}
// And so on...
That being said, you should think of NSObject
as a integral part of the ObjC runtime. There's little if any reason to implement your own root class outside of curiosity, investigation, or experimentation (which should, however, not be discouraged at all).