objective-c - 在 '' 类型的对象上找不到属性 'id'

标签 objective-c cocoa-touch properties

尝试读取或写入数组的 aVariable 时,我得到 Property 'aVariable' not found on object of type id。难道不应该知道我添加的对象是什么类吗?还注意到它可以使用 NSLog(@"%@",[[anArray objectAtIndex:0] aVariable]);

读取值

我是 Objective C 的初学者,所以它可能是一些我没有理解的简单东西。

一个对象

@interface AnObject : NSObject

@property (nonatomic,readwrite) int aVariable;

@end

另一个对象

@interface AnotherObject : NSObject

@end

测试.h

#import "test.h"

@implementation AnObject
@synthesize aVariable;

- (id)init
{
    self = [super init];
    if (self) {
        aVariable=0;
    }
    return self;
}  

@end

测试.m

@implementation AnotherObject

- (id)init
{
    self = [super init];
    if (self) { }
    return self;
}  

- (NSMutableArray*) addToArray
{
    NSMutableArray* anArray = [[NSMutableArray alloc] initWithCapacity:0];
    AnObject* tempObject = [[AnObject alloc] init];

    tempObject.aVariable=10;
    [anArray addObject:tempObject];

    // Property 'aVariable' not found on object of type 'id'
    [anArray objectAtIndex:0].aVariable=[anArray objectAtIndex:0].aVariable + 1; 

    // Property 'aVariable' not found on object of type 'id'
    NSLog(@" %i",[anArray objectAtIndex:0].aVariable); 

    // This works
    NSLog(@" %i",[[anArray objectAtIndex:0] aVariable]); 

    return anArray;
}

@end

最佳答案

这段代码:

[anArray objectAtIndex:0].aVariable

可以分为两部分:

[anArray objectAtIndex:0]

这将返回一个 id - 因为您可以将任何类型的对象放入数组中。编译器不知道此方法将返回什么类型。

.aVariable

这是在从数组返回的对象上请求属性 aVariable - 如上所述,编译器不知道这个对象是什么 - 它当然不会假设它是一个 AnObject,只是因为那是您之前添加的一两行。它必须自己评估每个陈述。因此编译器给你错误。

使用访问器方法时更宽容一点:

[[anArray objectAtIndex:0] aVariable];

这会给你一个警告(对象可能不会响应选择器)但它仍然会让你运行代码,幸运的是你的对象确实响应了那个选择器,所以你不要崩溃。然而,这不是一件值得信赖的事情。编译器警告是您的 friend 。

如果要使用点表示法,则需要告诉编译器从数组返回的对象类型。这称为转换。您可以分两步执行此操作:

AnObject *returnedObject = [anArray objectAtIndex:0];
int value = returnedObject.aVariable;

或者用一堆乱七八糟的括号:

int value = ((AnObject*)[anArray objectAtIndex:0]).aVariable;

额外的括号是允许您在转换时使用点符号所必需的。如果你想使用访问器方法,你需要更少的圆括号但更多的方括号:

int value = [(AnObject*)[anArray objectAtIndex:0] aVariable];

关于objective-c - 在 '' 类型的对象上找不到属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302674/

相关文章:

ios - 如何将 iPhone 应用程序常量(.h 类)和第三方框架添加到 watch 套件扩展中?

objective-c - 属性(property)不符合协议(protocol)

configuration - 在 Scala 中处理属性

objective-c - 从什么时候开始可以在类别中声明 Objective-C 2.0 属性?

ios - objective C下划线变量和自变量不同

ios - 在代码中创建 UIScrollView 子类,我应该在哪里添加 subview ?

iPhone:以编程方式将音频存储为铃声

基于 iPhone View 的应用程序转到主视图

ios - 未保存到核心数据数据库的对象

java - 注入(inject)静态属性值