简体   繁体   English

以编程方式在Objective-C中创建属性?

[英]create a property in an objective-c programmatically?

How can you create a property in objective-c programmatically? 如何以编程方式在Objective-C中创建属性?

Background: 背景:

  • so effectively, based on data you read in from a store, create properties on a class 如此有效,根据您从商店读取的数据,在类上创建属性
  • specifically I wanted to create some typed properties to represent my "eventtypes" which I store in core data - so whilst the EventTypes are in coredata in the EventTypes entity, I could read them in at run time to a class and then reference them list "EventTypes.ACTIVE_EVENT" 特别是我想创建一些类型化的属性来表示我存储在核心数据中的“事件类型”-因此,尽管EventTypes位于EventTypes实体的coredata中,但我可以在运行时将其读取到类中,然后将其引用为列表” EventTypes.ACTIVE_EVENT”

The overall goal I had in mind was: 我想到的总体目标是:

  • keep types in the core data store modelled 对核心数据存储中的类型进行建模
  • but still have a way to easily access a managed object type instance (eg ACTIVE_EVENT) programmatically via use of the simple property approach . 但是仍然可以通过使用简单属性方法以编程方式轻松访问托管对象类型实例(例如ACTIVE_EVENT)。

A regular Objective C property normally causes the compiler to generate code for getters and setters. 常规的Objective C属性通常会使编译器为getter和setter生成代码。 But an iOS app isn't allowed to add any new executable code due to security sandbox restriction, so at run time you can't programmatically do this the same way as the compiler. 但是由于安全沙箱限制,iOS应用程序不允许添加任何新的可执行代码,因此在运行时,您无法以编程方式以与编译器相同的方式执行此操作。

What you can do is use the Objective C runtime to emulate getting and setting a property, perhaps using the forwardInvocation: and methodSignatureForSelector: methods for handling unrecognized messages. 您可以做的是使用Objective C运行时来模拟获取和设置属性,也许使用forwardInvocation:和methodSignatureForSelector:方法来处理无法识别的消息。 The backing property state data could be stored, for instance, in some sort of mutable dictionary of property elements held by the class object. 支持属性状态数据可以存储在例如类对象持有的某种可变的属性元素字典中。 Then the object might act (a bit more slowly) as if it had implemented the property you created programmatically. 然后,该对象的行为(稍微慢一些)就好像它已经以编程方式实现了您创建的属性一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM