如何在NSArray中存储多类型数据?

时间:2014-06-30 07:14:27

标签: iphone objective-c ios7 nsarray

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

2 个答案:

答案 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)

  1. 使用@456,与[NSNumber numberWithInt:456]相同

  2. 使用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
        }
    }