13、集合类

2015-08-03  本文已影响29人  HQ今日磨墨

集合类

NSNumber *int1 = [NSNumber numberWithInt:1];

其中占位符 %li 代表 long int

nsarray.jpg

  上图创建了一个NSArray的对象,其中 (id),..., 表示可以在其中加入多个对象,最后有个 nil 。当系统读到 nil 之后就不会再读下去,所以在后面添加对象是没有效果的。(在开发中也会遇到这样的情况,在(id)中加入了多个对象,运行时却发现数据都没有传入进去,其中很大的可能就是传入的第一个值已经被赋予了 nil ,所以包括它本身和后面的对象都没有被存储进去

nsarray2.jpg

  由上图可以了解到, 在NSArray当中,你可以存放相同的对象,不过可以看到,它们的内存地址是相同的。

NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject:tempPerson];
[mutableArray addObject:int1];
[mutableArray removeObjectAtIndex:0];
[mutableArray replaceObjectAtIndex:0 withObject:tempPerson];

  提取对象(其实就是对象指针地址)的方法,前面的 id 是因为我们也许不知道提取的对象的类型是什么,所以用 id:

id object = [mutableArray objectAtIndex:0];

  当然你也可以对object的类型做一个识别,会显得更加地安全:

id object = [mutableArray objectAtIndex:0];
if ([[object class] isSubclassOfClass:[NSNumber class]]) {
      NSInteger intValue = [(NSNumber *)object integerValue];
      NSLog(@"intValue = %li", intValue);
} else if ([[object class] isSubclassOfClass:[BLPerson class]]) {
       [(BLPerson *)object sayMyInfo];
}
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectAndKeys:tempPerson, @"person", int1, @"int", nil];
// 注意这个方法的key是写在后面的,这里使用字符串做了key,当然也可以用其他的对象型

  我们也可以对字典中的数据机型提取,下面提取了它的键值:

NSArray *allKeys = [dictionary allKeys];
for (int i = 0; i < [allKeys count]; i++) {
      NSString *key = allKeys[i];
      id object = [dictionary valueForKey:key];
      if ([[object class] isSubclassOfClass:[NSNumber class]]) {
      NSInteger intValue = [(NSNumber *)object integerValue];
      NSLog(@"intValue = %li", intValue);
      } else if ([[object class] isSubclassOfClass:[BLPerson class]]) {
       [(BLPerson *)object sayMyInfo];
      }
}
// 也可以用快速遍历法
for (NSString *key in allKeys) {
    id object = [dictionary valueForKey:key];
    if ([[object class] isSubclassOfClass:[NSNumber class]]) {
      NSInteger intValue = [(NSNumber *)object integerValue];
      NSLog(@"intValue = %li", intValue);
    } else if ([[object class] isSubclassOfClass:[BLPerson class]]) {
       [(BLPerson *)object sayMyInfo];
    }
}
NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] init];
[mutableDic setValue:tempPerson forKey:@"person"];
[mutableDic setValue:int1 forKey:@"int"];

[mutableDic removeObjectForKey:@"person"];

[mutableDic setValue:[NSNumber numberWithDouble:3.14] forKey:@"int"];
上一篇 下一篇

猜你喜欢

热点阅读