iphone - NSArray如何存储多类型数据?

标签 iphone objective-c ios7 nsarray

NSArray *pets = [NSArray arrayWithObjects:@"Cat", @"Dog", @"Rat", nil];

//如何在 @"Rat"对象之后将 int 值 456 存储在这个数组中,+ pet 是 NSString 类型,所以它不会在 while 循环中生成错误...???那么我应该使用什么数据类型作为可以表示所有 nextObject 值/对象的 pet 指针

NSEnumerator *enumerator = [pets objectEnumerator];
NSString *pet;

while (pet = [enumerator nextObject]) {
NSLog(@"Pet: %@", pet);
}

最佳答案

由于 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;
  }
}

或者 while 循环:

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;
   }
}

关于iphone - NSArray如何存储多类型数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24484726/

相关文章:

iphone:接到电话时通知?

ios - iOS中一个xib,多个类没有继承?

ios - 包含基于 xcode 方案的 header

iPhone Safari 以不同的方式呈现 .mobi (dot mobi) 域。但具体如何呢?

iphone - 从 URL iphone sdk 将图像加载到 tableView

iphone - iOS 中的闹钟应用程序

objective-c - swift : "Cannot assign value of type ' 项目 !' to type ' 项目!”

ios7 - 处理 UITextView 中 NSAttributedString 的 UIContentSizeCategoryDidChangeNotification

带有 UISlider 的 iOS7 自定义 setMaximumTrack 图像不显示在设备上

ios - 如何在 ios 中操作 UITextView 的个性?