对于继承对象的集合中的对象 [英] for object in collection where object inherits

查看:146
本文介绍了对于继承对象的集合中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,对于(Foo * foo in fooList)来说,

  ... 

code>

更喜欢以下哪一项?

 <$ c $ f $ ... 
$ b $(foo * f in foo){
// A:
if([f isMemberOfClass:[Foo class] ])... //不包含Bar的

// B:
if([f isKindOfClass:[Foo class]])... // Foos和Bars
}


解决方案


$ b $ 中的 foo 对于()部分来说只是一个提示给编译器,这样可以发出相关的错误信息。在运行时,所有的对象都只是对象,只要它们全部实现了块中使用的方法,就不会有错误。例如:

  NSString * aString = @20; 
[anArray addObject:aString];
for(NSNumber * foo in anArray)
{
NSLog(@%d,[foo intValue]);



$ b $ p
$ b

会迭代数组中的所有对象并将intValue发送给每个<不管它们是什么类型,包括最后的NSString。如果每个对象都实现 intValue ,它就可以正常工作(就像NSString一样)。如果数组中有一个对象没有实现intValue,则最有可能抛出异常。


In objective-c, is

for (Foo *foo in fooList) ...

more like which of the following

@interface Bar : Foo ...

for (Foo *f in fooList) {
    // A:
    if ([f isMemberOfClass:[Foo class]]) ... // dont include Bar's

    // B:
    if ([f isKindOfClass:[Foo class]]) ... // both Foos and Bars
}

解决方案

It's not like either.

The type of foo in the for() part is only a hint to the compiler so it can give out the relevant error messages. At run time, all the objects are just objects and as long as they all implement the methods used in the block, there will be no errors. For example:

NSString* aString = @"20";
[anArray addObject: aString];
for (NSNumber* foo in anArray)
{
    NSLog(@"%d", [foo intValue]);
}

will iterate over all the objects in the array and send intValue to each one no matter what type they are including the NSString at the end. If every object implements intValue it will work just fine (as NSString does). If there is an object in the array that does not implement intValue, an exception will most likely be thrown.

这篇关于对于继承对象的集合中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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