What use cases are there for defining a new root class?

前端 未结 4 438
傲寒
傲寒 2020-12-10 04:12

We know that in Objective-C there are two main root classes: NSObject and NSProxy. There are other roots (mainly for private and legacy purposes)

4条回答
  •  长情又很酷
    2020-12-10 04:56

    There are two primary reasons to create a new root class; proxying & a new object model.

    When proxying, it can be useful to implement a new root class such that you can basically handle any and all of the class/object's behaviors in a custom fashion. See NSProxy.

    The Objective-C runtime is flexible enough that you can support a new object model quite easily (where easily discounts the inherent complexity of creating such a beast in the first place). Actually, many of the behaviors that are considered inherent to the runtime -- KVC, KVO, etc.. -- are implemented as a part of the NSObject class itself.

    I know of at least one company that -- as of about 8 years ago, at least -- had implemented their own object model as a part of building their ~500k LOC financial analysis engine.

    The key, though, is that if you go this route, you don't try to make your classes interact with Foundation/CF/AppKit/UIKit, etc. If you need that, just subclass NSObject already!

    It is interesting to note that NSManagedObject is effectively a root class in that it does some pretty seriously custom stuff, but it is a subclass of NSObject so subclasses of NSManagedObject are inter-operable with the rest of the system.

提交回复
热议问题