【发布时间】:2015-09-09 12:00:16
【问题描述】:
更新:
我将问题归结为根本无法在下面看到的类上使用键值编码
#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
@interface CMTransformation : NSObject
@property(nonatomic) GLKVector3 position;
@property(nonatomic) GLKVector3 scale;
@property(nonatomic) GLKVector3 rotation;
@property(nonatomic) GLKVector3 anchor;
@property(nonatomic) GLKMatrix4 matrix;
- (GLKMatrix4)calculateMatrixWithParentTransformation:(CMTransformation *)parentTransformation;
@end
根据我的理解和经验,我应该能够将非 NSObject 作为 NSValue 提取出来,但是,我发现使用 KVC 语法无法访问这些项目(定义为联合):
CMTransformation* trans = [[CMTransformation alloc] init];
temp = [trans valueForKey:@"position"];
同样,如果我尝试访问底层变量:
CMTransformation* trans = [[CMTransformation alloc] init];
temp = [trans valueForKey:@"_position"];
这两个都抛出异常,因为找不到密钥。我在这里错过了什么?
上一个问题
我编写了一些代码,允许我使用诸如“transformation.position”之类的字符串访问(有点)任意结构
由于某种原因,当我尝试从 NSObject 读取属性时,代码在第二次跳转时停止工作。这里是
NSString* property = actionDetails[@"Property"];
PropertyParts = [[property componentsSeparatedByString:@"."] mutableCopy];
int count = [PropertyParts count];
id current_object = initial_object;
for(int i = 0; i < count; i++)
{
NSString* current_part = PropertyParts[i];
current_object = [current_object valueForKey:current_part];
}
我已经尝试了所有可能的属性访问语法,包括 Property、property 和 _property。
这是自定义的 NSObject 声明
#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
@interface CMTransformation : NSObject
@property(nonatomic) GLKVector3 position;
@property(nonatomic) GLKVector3 scale;
@property(nonatomic) GLKVector3 rotation;
@property(nonatomic) GLKVector3 anchor;
@property(nonatomic) GLKMatrix4 matrix;
- (GLKMatrix4)calculateMatrixWithParentTransformation:(CMTransformation *)parentTransformation;
@end
另外,在第一个循环之后,我可以看到调试器说 CMTransformation* 正在填充 currrent_object,所以我不知道为什么我不能访问它的属性?
【问题讨论】:
-
current_object是 CMTransformation 吗?你为什么要把它变成id的类型而不是明确的? -
这意味着能够迭代任何嵌套的 NSObject 结构,而不仅仅是给出的具体示例。在 ARC 中,您甚至可以对类成员变量使用 KV 编码。
-
你可以尝试实现 -valueForUndefinedKey: 来修补这种情况。 (或者可能 +resolveInstanceMethod:)
-
@nielsbot 本来打算这样做,但是使用 ARC,我们仍然无法动态访问它以将其传回我的知识,因为我们不允许使用像 object_getInstanceVariable 这样的低级函数。我应该注意到,如果我们能找到一种方法来获取指向它的指针,就很容易检测到它是什么类型。
-
假设您有关联的 ivar,则存在 ivar_getOffset。我想我可能有一个可以发布的工作示例代码......它几乎可以工作了。
标签: ios objective-c introspection key-value-coding