为什么我需要投可以称得上是NSArray中的项目的方法之前? [英] Why do I need to cast before a method of an item of a NSArray can be called?

查看:80
本文介绍了为什么我需要投可以称得上是NSArray中的项目的方法之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的Objective-C的。目前移植我自己从C#/ Java库客观℃。

I am fairly new to Objective-C. Currently porting my own library from C#/Java to objective C.

我现在遇到一个很奇怪的问题对我来说。

I now run into a very strange problem for me.

我有一个的NSArray 与几个注意的对象。我想转对这些说明的:

I have a NSArray with several Note objects. I want to transpose on of these notes:

 //Note.h
 - (Note *) transpose: (int) semitones; 

 //Main
 NSArray *notes = [get it from somewhere];
 Note *transposedNote = [[notes objectAtIndex:0]transpose:1]; //Doesn't compile
 Note *transposedNote = [(Note*)[notes objectAtIndex:0]transpose:1]//Does compile

这是发生,因为已经有一个在一般的库中可用的方法是什么?

Is this happening because there is already a transpose method available in the general libraries?

我认为,由于客观-C在运行时的动态性质,将被检查哪一类 objectAtIndex 的回报,然后将邮件发送给它?

I thought due to the dynamic nature of objective-C at runtime it would be checked which class objectAtIndex returns and then sends the message to it?

推荐答案

是的,错误的是,因为已经有一个转:方法了AppKit。而你也正确,它通常当你有实现具有相同名称的方法两个不相关的类不会导致错误。你得到一个错误的原因是因为这两种方法中的任何返回不兼容的类型采取不兼容的类型作为参数即可。在特定情况下,你看到的两个问题:

Yes, the error is because there's already a transpose: method in AppKit. And you're also right that it normally doesn't cause an error when you have two unrelated classes implementing methods with the same name. The reason you get an error is because the two methods either return incompatible types or take incompatible types as arguments. In your particular case, you're seeing both problems:


  • - [NSResponder类转:] 需要一个 ID 并返回无效

  • - [注转:] 需要一个 INT 并返回 ID

  • -[NSResponder transpose:] takes an id and returns void
  • -[Note transpose:] takes an int and returns an id

这些是完全不兼容的类型,并且编译器的确实的需要知道涉及即使它不知道将被称为什么确切的方法的类型。

These are totally incompatible types, and the compiler does need to know the types involved even if it doesn't know what exact method is going to be called.

这篇关于为什么我需要投可以称得上是NSArray中的项目的方法之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆