Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 对象指向_Objective C_Oop - Fatal编程技术网

Objective c 对象指向

Objective c 对象指向,objective-c,oop,Objective C,Oop,我试图访问实现文件中的对象,其中的方法如下所示: -booleanhumansalive:idhumanobj;但是,Xcode抱怨不存在这样的对象,构建失败 在主文件main.m中,我将在main函数中写入以下内容: int main(int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Human *human = [[Human alloc]

我试图访问实现文件中的对象,其中的方法如下所示: -booleanhumansalive:idhumanobj;但是,Xcode抱怨不存在这样的对象,构建失败

在主文件main.m中,我将在main函数中写入以下内容:

int main(int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    Human *human = [[Human alloc] init];
    MyHuman *myhuman = [[MyHuman alloc] init];

    [human create:@"John Doe" age:25];
    if ([human humanIsAlive:myhuman]) {
        NSLog(@"%@ is alive and well.", myhuman.humanName);
    } else {
        NSLog(@"%@ is dead and gone.", myhuman.humanName);
    }

    [pool drain];
    return 0;
}
以下是Xcode抱怨的代码:

- (Boolean)humanIsAlive:(id)humanobj {
    if (humanobj.living == YES) {
        return YES;
    }
    return NO;
}
这似乎是合法的,但Xcode抱怨说,这个对象中不存在这样的属性,也不存在这样的对象


帮助?

类型id为的对象上的属性无法安全地解析为任何一个对象上的实例方法,因此该语言禁止它们。此外,如果你能给id本身添加属性,我们就会有一种糟糕的语言

您所需要做的只是更具体:

- (BOOL) humanIsAlive:(MyHuman*)humanobj { //... }

如果您确实需要处理两种不同类型的对象,请更安全地使用-isKindOfClass:,然后在适当的位置强制转换对象以使用其属性

我试图做的是等待用户输入一个对象并从那里访问属性。如果您需要一个方法来处理两种不同类型的对象,而这两种类型的对象在设计上永远不会发生,那么就声明它接受一个id类型的对象,然后使用-isKindOfClass:测试它的类,并适当地强制转换。