说明:OC里的集合,数组,等都可以 类比java中集合数组的处理。
字典
NSDictionary *dict1=[NSDictionary dictionaryWithObject:@"one" forKey:@"key1"];
NSLog(@"%@",dict1); //以多个元素进行初始化
NSDictionary *dict2=[NSDictionary dictionaryWithObjectsAndKeys:@"one", @"key1",@"two",@"key2",@"three",@"key3", nil];
NSLog(@"%@",dict2);
NSLog(@"----%@",[dict2 objectForKey:@"key2"]);
//遍历NSDictionary
NSArray *objs = [dict2 allKeys];
for (NSString *str in objs) {
NSLog(@"----%@",str);
}
打印结果
2016-01-31 16:33:27.817 OC[1766:156610] {
key1 = one;
}
2016-01-31 16:33:27.818 OC[1766:156610] {
key1 = one;
key2 = two;
key3 = three;
}
2016-01-31 16:33:27.818 OC[1766:156610] ----two
2016-01-31 16:33:27.819 OC[1766:156610] ----key1
2016-01-31 16:33:27.819 OC[1766:156610] ----key3
2016-01-31 16:33:27.819 OC[1766:156610] ----key2
Program ended with exit code: 0
集合
//使用集合
//使用数组
NSArray *array = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];
//快速遍历
for (NSString *str in array) {
NSLog(@"----%@",str);
}
//索引访问
for (NSInteger n; n< array.count; n++) {
NSLog(@"%@",[array objectAtIndex:n]);
}
//使用NSEnumerator对象
NSEnumerator *enumeator = [array objectEnumerator];
NSString *item = nil;
while ((item =[enumeator nextObject])) {
NSLog(@"%@",item);
}
NSLog(@"last object %@",[array lastObject]);
NSLog(@"first object %@",[array objectAtIndex:0]);
打印的值:
2016-01-31 16:06:44.836 OC[1675:149420] ----one
2016-01-31 16:06:44.837 OC[1675:149420] ----two
2016-01-31 16:06:44.837 OC[1675:149420] ----three
2016-01-31 16:06:44.837 OC[1675:149420] one
2016-01-31 16:06:44.837 OC[1675:149420] two
2016-01-31 16:06:44.837 OC[1675:149420] three
2016-01-31 16:06:44.837 OC[1675:149420] one
2016-01-31 16:06:44.837 OC[1675:149420] two
2016-01-31 16:06:44.837 OC[1675:149420] three
2016-01-31 16:06:44.838 OC[1675:149420] last object three
2016-01-31 16:06:44.838 OC[1675:149420] first object one
Program ended with exit code: 0
//认识可变性
NSMutableArray *array = [NSMutableArray array];
[array addObject:@"one"];
[array addObject:@"two"];
[array addObject:@"three"];
NSLog(@"删除之前%@",array);
[array removeObject:@"one"];
NSLog(@"删除之后%@",array);
[array removeObjectAtIndex:0];
[array replaceObjectAtIndex:0 withObject:@"oneoneone"];
NSLog(@"%@",array);
2016-01-31 16:40:34.118 OC[1785:159199] 删除之前(
one,
two,
three
)
2016-01-31 16:40:34.119 OC[1785:159199] 删除之后(
two,
three
)
2016-01-31 16:40:34.119 OC[1785:159199] (
oneoneone
)
Program ended with exit code: 0
字符串:NSString,NSMutableString
NSString *str;
NSString *cardName = @"Ace";
NSString *cardSuit = @"Spades";
str = [NSString stringWithFormat:@"The winning card is %@ of %@.",cardName,cardSuit];
NSLog(@"-----%@",str);
//-----The winning card is Ace of Spades.
NSString *str2 = @"this is a string of words";
NSArray *words = [str2 componentsSeparatedByString:@" "]; //分割字符串 类似于java split
NSLog(@"%@",words);