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

后端 未结 4 1193
猫巷女王i
猫巷女王i 2020-12-15 04:38

Given this:

Person.h:

@interface Person 
{
}
- (void) sayHello;
@end

Person.m:

#import \"Person.h\"

@implementa         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-15 05:31

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

提交回复
热议问题