本文介绍了如何在Objective-C中实例化一个不继承NSObject的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此:

Person.h:

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

Person.m:

#import "Person.h"

@implementation Person 

- (void)sayHello 
{
    printf("%s", "Steve");
}

@end

?我尝试这样:

Person *p = [Person new];

这不起作用,也不:

Person *p = [Person alloc];

[UPDATE]

告诉,我已经尝试继承从NSObject,新和alloc工作。我只是好奇,如果我们可以实例化一个不继承NSObject的类。

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?

推荐答案

你绝对可以这样做。你的类只需要实现 + alloc 本身, NSObject 的方式。在基础上,这只是意味着使用 malloc()来抓取足够大的内存块,以适应定义类的实例的结构。

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.

引用计数的内存管理也会很好( retain / release );这实际上是。您可以采用协议并实施这些方法。

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.

如需参考,您可以查看,它是一个根类ObjC类,如 NSObject ,Apple在其开源库中为Objective-C运行时提供:

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

话虽如此,你应该把 NSObject 看作ObjC运行时的一个组成部分。在好奇心,调查或实验之外,实现你自己的根类根本没有任何理由(但是,应该不要灰心)。

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

这篇关于如何在Objective-C中实例化一个不继承NSObject的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:25