#import
void testSet();
void testDictionary();
int main(int argc, const char * argv[])
{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
testSet();
NSLog(@"\n\n------------------------------\n\n");
testDictionary();
[pool drain];
return 0;
}
void testDictionary()
{
// 此种方式创建集合对象,最后都要以nil结尾
NSMutableDictionary *mdict=[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"James",@"name",
[NSNumber numberWithInteger:20],@"age",
@"1568956556",@"phoneNo",nil];
[mdict setObject:[NSNumber numberWithFloat:66.6] forKey:@"weight"];
[mdict removeObjectForKey:@"phoneNo"];
// 根据key取value,没找到返回空
NSLog(@"name=%@,age=%d,phontNo=%@,weight=%.2f",
[mdict objectForKey:@"name"],
[[mdict objectForKey:@"age"] intValue],
[mdict objectForKey:@"phoneNo"],
[[mdict objectForKey:@"weight"] doubleValue]);
// @方式快速创建出来的都是不可变对象
NSDictionary *dict=@{
@"name":@"Bruce",
@"age":[NSNumber numberWithLong:28],
@"phoneNo":@"1868955656",
@"weight":[NSNumber numberWithDouble:72.2]};
NSLog(@"dict=%@",dict);
// for循环方式遍历字典
NSArray *keys=[mdict allKeys];
int i;
for(i=0;i<[mdict count];i++)
{
id key = [keys objectAtIndex:i];
id val = [mdict objectForKey:key];
NSLog(@"%@=%@",key,val);
}
// 字典自身的利用block遍历方法
[dict enumerateKeysAndObjectsUsingBlock:
^(id key,id obj,BOOL *stop)
{
NSLog(@"%@=%@",key,obj);
}];
}
void testSet()
{
NSSet *set = [NSSet setWithObjects:@"123",@"123",@"222",
[[[NSObject alloc] init] autorelease],@"333",@"444",@"222",nil];
//Set中元素是无序且唯一
NSLog(@"setCount=%d andSet=%@",[set count],set);
// anyObject多次调用返回同一个值,但这个值是不确定的
NSLog(@"[set anyObject]=%@",[set anyObject]);
NSLog(@"[set anyObject]=%@",[set anyObject]);
NSLog(@"[set anyObject]=%@",[set anyObject]);
NSMutableSet *mset=[NSMutableSet set];
[mset addObjectsFromArray:[NSArray arrayWithObjects:
@"123",@"123",@"222",[[[NSObject alloc] init] autorelease],
@"333",@"444",@"222",nil]];
[mset removeObject:@"222"];
NSLog(@"msetCount=%d and mset=%@",[mset count],mset);
}
NSSet:
特点:
无序,唯一,仅限存非空的OC对象,本身初始化后内容不可变,其子类NSMutableSet为可变;
常用方法:
+(id)setWithObjects:(id)obj,...,nil;
-(NSUInteger)count;
// 返回任意的一个对象
-(id)anyObject;
NSMutableSet:
常用方法:
-(void)addObjectsFromArray:(NSArray *)from;
-(void)removeObject:(id)obj;
NSDictionary:
特点:
类似java中Map,键值对形式保存数据,无序,key唯一,key值仅限非空OC对象,
value值仅限OC对象,本身初始化后内容不可变,子类NSMutableDictionary可变;
常用方法:
+(id)dictionaryWithObjects:(NSArray *)objs forKeys:(NSArray *)keys;
//动态参数顺序为 val,key,val,key,...,nil
+(id)dictionaryWithObjectsAndKeys:(id)obj,...,nil;
@快速创建方式: //返回不可变的字典
@{key1:value1,key2:value2,...};
// 根据key获取值,便捷形式为 dict[key]
-(id)objectForKey:(id
//获取保存的键值对个数
-(NSUInteger)count;
//返回所有key的集合
-(NSArray *)allKeys;
//利用block遍历
-(void)enumerateKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop)block;
NSMutableDictionary:
-(void)setObject:(id)obj forKey:(id
-(void)removeObjectForKey:(id)key;