NSArray *pets = [NSArray arrayWithObjects:@"Cat", @"Dog", @"Rat", nil];
//在@" Rat"之后如何在这个数组中存储int值456?对象,+ pet是NSString类型所以不会在while循环中生成错误...... ???那么我应该使用哪种数据类型来表示可以表示所有nextObject值/对象的宠物指针
NSEnumerator *enumerator = [pets objectEnumerator];
NSString *pet;
while (pet = [enumerator nextObject]) {
NSLog(@"Pet: %@", pet);
}
答案 0 :(得分:5)
由于NSArray
只保存对象,因此无法添加整数,因此需要将其包装在NSNumber
中。
NSArray *pets = @[@"Cat", @"Dog", @"Rat", @456];
这将适用于示例中的循环,但如果要调用任何NSString
方法,则需要检查类型:
for(id pet in pets) {
if(![pet isKindOfClass:[NSString class]) {
// It not a string, just continue to the next object.
continue;
}
}
或者循环:
id pet;
NSEnumerator *enumerator = [pets objectEnumerator];
while (pet = [enumerator nextObject]) {
if(![pet isKindOfClass:[NSString class]) {
// It not a string, just continue to the next object.
continue;
}
}
答案 1 :(得分:-3)
使用@456
,与[NSNumber numberWithInt:456]
相同
使用id。即:
id pet;
while (pet = [enumerator nextObject]) {
NSLog(@"Pet: %@", pet); // maybe unsafe if only a subset of the objects in the array can execute the methods
// if you want to unwrap the pet to the concrete class, cast it with (NSString *)pet
// but make sure the object is of correct type
if ([pet isKindOfClass: [NSString class]]) {// use isMemberOfClass for exactly this class and isKindOfClasses for this class and subclasses of it
// here you are sure it is a NSString
}
}