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?
Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.
The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
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).
You must:
Of course, neither of the other two fit into Objective-C storage management, and their call protocols, etc, are different.
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