Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a class in Objective-C that don't inherit from NSObject

Tags:

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?

like image 953
Hao Avatar asked Jan 21 '12 15:01

Hao


People also ask

Can Objective-C class inherit from Swift class?

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.

What does NSObject mean?

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.


2 Answers

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).

like image 80
jscs Avatar answered Sep 20 '22 07:09

jscs


You must:

  1. Inherit from NSObject,
  2. Do a "poor man's" class with your own mallocs, etc, or
  3. Use Objective-C++ and create a C++ class.

Of course, neither of the other two fit into Objective-C storage management, and their call protocols, etc, are different.

like image 41
Hot Licks Avatar answered Sep 19 '22 07:09

Hot Licks