Why do Objective-C objects have to be dynamically allocated?

前端 未结 3 1489
野趣味
野趣味 2020-12-30 03:41

Why do Objective-c objects have to be dynamically allocated? Why do I have to make it a pointer to an object, unlike in C++ I can create them on stack? Thanks.

3条回答
  •  灰色年华
    2020-12-30 04:30

    This is because of the way Objective-C uses dynamic or late binding. Unlike C++ where you'll always have the choice between calling a function of a class by it's object or via a pointer of the same class or even of a superclass. In the latter case polymorphism is required.

    However, in Objective-C there exists always the ability to determine the correct function at runtime. The difference is, that for example in C++ the compiler has to ensure, that the used function exists, whereas in Objective-C the compiler doesn't really care, the runtime system decides only.

提交回复
热议问题