【Objective-C学习记录】第二天
1.不可变数组:
NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",nil];
判断元素是否存在:
BOOL res = [array containsObject:@"1"];
获取最后一个元素:
NSString *str = [array lastObject];//3
获取第一个元素:
NSString *str = [array firstObject];//1
根据下标获取元素:
NSString *str = [array objectAtIndex:2];//3
根据元素输出下标:
int index = (int)[array indexOfObject:@"2"];
数组遍历:
1.for循环
2.快速枚举(需要数组元素类型完全一致)
for(NSString *str in array)
NSLog(@"%@",str);
2.可变数组:
NSMutableArray *array = [[NSMutableArray alloc] init];
添加元素:
[array addObject:p];
[array addObjectsFromArray:array2];
删除所有元素:
[array removeAllObjects];
删除最后一个元素:
[array removeLastObject];
删除指定元素:
[array removeObject:@"2"];
交换元素位置:
[array exchangeObjectAtIndex:0 withObjectAtIndex:1];
字典:
//内存存储不是连续的
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"2",@"3",nil] forKeys:[NSArray arrayWithObjects:@"a",@"b",@"c",nil]];
NSDictionary *dict = @{@"1":@"a",@"2":@"b",@"3":@"c"};
NSString *value = [dict valueForKey:@"a"];//1
NSString *value2 = [dict objectForKey:@"a"];//1
NSString *allValues = [dict allValues];//(1,2,3)
NSString *allKeys = [dict allKeys];//(a,b,c)
查找值:
NSArray *array = [dict objectsForKeys:[NSArray arrayWithObjects:@"a",@"b",@"d",nil] notFoundMaker:@"Not Found"];//如果找到值则返回,没找到则返回Not Found
NSLog(@"%@",array);//(1,2,"Not Found")
遍历字典:
1.for in
for(NSString *key in dict)
NSLog(@"%@ = %@",key,[dict objectForKey:key]);
2.枚举器
NSEnumerator *en = [dict keyEnumerator];
id key = nil;
while(key = [en nextObject])
NSLog(@"Key = %@",key);
block方法
[dict enumerateKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop){}];
可变字典:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"1" forKey:@"a"];
[dict setObject:@"2" forKey:@"b"];
删除所有值对:
[dict removeAllObjects];
删除指定值对:
[dict removeObjectForKey:@"b"];
[dict removeObjectsForKeys:[NSArray arrayWithObjects:@"a",@"b",nil]];