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

时间:2011-11-28 21:35:47

标签: objective-c cocoa-touch properties

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

读取值

我是Objective C的初学者,所以我可能会遇到一些简单的事情。

AnObject

@interface AnObject : NSObject

@property (nonatomic,readwrite) int aVariable;

@end

AnotherObject

@interface AnotherObject : NSObject

@end

test.h

#import "test.h"

@implementation AnObject
@synthesize aVariable;

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

@end

test.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

2 个答案:

答案 0 :(得分:38)

此代码:

[anArray objectAtIndex:0].aVariable

可以分为两部分:

[anArray objectAtIndex:0]

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

.aVariable

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

使用存取方法时,它更宽容一些:

AnObject

这会给你一个警告(该对象可能没有响应选择器)但它仍然允许你运行代码,幸运的是你的对象 响应那个选择器,所以你不要崩溃。然而,依靠这不是一件安全的事情。编译器警告是你的朋友。

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

[[anArray objectAtIndex:0] aVariable];

或者是一堆括号:

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

需要额外的括号以允许您在施法时使用点表示法。如果要使用访问器方法,则需要更少的圆括号,但需要更多的方括号:

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

答案 1 :(得分:1)

-[NSArray objectAtIndex:]返回id指针。由于id不包含有关协议的信息,因此编译器无法知道对象是否具有您声明的属性;这就是它抱怨的原因。

您可以通过强制转换objectAtIndex:的返回值或使用getter / setter表示法来解决此问题,即[anArray objectAtIndex:0] setAVariable:...]。还要确保导入协议定义,否则编译器可能也不知道声明的方法并发出警告。

相关问题