在Objective-C中使用(id) [英] Using (id) in Objective-C

查看:75
本文介绍了在Objective-C中使用(id)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要对两个不同的自定义对象进行操作的函数.我的第一个想法是接受参数作为(id)并对id对象进行操作.但是,我似乎还不太清楚该怎么做.

I have a function that I want to operate on two different custom objects. My first thought was to accept the argument as an (id) and operate on the id object. I can't quite seem to figure out how to do that, however.

两个类(例如苹果和橘子)都具有接口变量:

Both classes (say apples and oranges) have interface variables:

NSDecimalNumber *count;

我想做类似的事情:

-(NSDecimalNumber*)addCount:(id)addObject{

    return [count decimalNumberByAdding:addObject.count];
}

我似乎无法弄清楚实现这一点的语法.这是正确的方法,还是最好将其子类化(从水果类中继承)并在父类上进行操作?

I can't seem to figure out the syntax to make that happen. Is this the proper approach, or would it be better to subclass (from say a fruit class) and operate on the parent class?

-(NSDecimalNumber*)addCount:(Fruit*)addFruit{

    return [count decimalNumberByAdding:addFruit.count];
}

推荐答案

虽然您可以向任何对象(id)发送消息-属性访问器要求编译器知道您要处理的类型-这是因为property访问器是围绕调用特定的getter和setter方法的语法糖.

While you can send a message to any object (id) - property accessors require that the compiler be aware of the type you are dealing with - this is because property accessors are syntactic sugar around calling specific getter and setter methods.

您有几种解决方法:

  1. 而不是访问count属性,而是调用相应的[getCount]方法.

  1. Instead of accessing the count property, call the corresponding [getCount] methods.

如果不同的类具有此方法的不同版本,则可以使用运行时类型检查:

If the different classes have different versions of this method, you can use a runtime type check:

为两种类型都提供基类,以便您可以传递比(id)更特定的内容.

Provide a base class for both types so that you can pass in something more specific than (id).

动态类型检查的示例:

if( [object isKindOfClass:[Apple Class] )
   // call one overload of getCount
else if( [object isKindOfClass:[Orange Class] )
   // call another overload of getCount

就个人而言,我喜欢在代码中使用强类型输入,因为这样可以更轻松地理解其意图.它还允许IDE通过智能感知,静态分析和重构功能来支持您的编码工作.因此,在您的情况下,我将使用#3或#4作为方法-取决于继承是否真的适合该问题.

Personally, I favor strong typing in my code because it makes it easier to understand the intent. It also allows the IDE to support your coding effort with intellisense, static analysis, and refactoring features. So, in your case, I would use either #3 or #4 as an approach - depending on whether inheritance is really appropriate for the problem.

这篇关于在Objective-C中使用(id)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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