- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
尝试读取或写入数组的 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
#import "test.h"
@implementation AnObject
@synthesize aVariable;
- (id)init
{
self = [super init];
if (self) {
aVariable=0;
}
return self;
}
@end
@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/
例如,我有一个父类Author: class Author { String name static hasMany = [ fiction: Book,
代码如下: dojo.query(subNav.navClass).forEach(function(node, index, arr){ if(dojo.style(node, 'd
我有一个带有 Id 和姓名的学生表和一个带有 Id 和 friend Id 的 Friends 表。我想加入这两个表并找到学生的 friend 。 例如,Ashley 的 friend 是 Saman
我通过互联网浏览,但仍未找到问题的答案。应该很容易: class Parent { String name Child child } 当我有一个 child 对象时,如何获得它的 paren
我正在尝试创建一个以 Firebase 作为我的后端的社交应用。现在我正面临如何(在哪里?)找到 friend 功能的问题。 我有每个用户的邮件地址。 我可以访问用户的电话也预订。 在传统的后端中,我
我主要想澄清以下几点: 1。有人告诉我,在 iOS 5 及以下版本中,如果您使用 Game Center 设置多人游戏,则“查找 Facebook 好友”(如与好友争夺战)的功能不是内置的,因此您需要
关于redis docker镜像ENTRYPOINT脚本 docker-entrypoint.sh : #!/bin/sh set -e # first arg is `-f` or `--some-
我是一名优秀的程序员,十分优秀!