尝试读取或写入数组的 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/