Objective-C 学习记录6--dictionary
1.NSDictionary 和NSMutableDictionary
NSDictionary dictionaryWithObjectsAndKeys:~,nil
使用键值对创建字典,用nil标志结束
NSDictionary initWithObjectsAndKeys:
使用键值对初始化字典,也用nil来表示结束.
dictionary count 计算其字典的长度.
dictionary keyEunmerator 将key全部存在NSEunmerator中,可以快速枚举其中的key的值.
dictionary objectForKey: key 通过key来查询值.
demo:
代码语言:javascript复制#import <UIKit/UIKit.h>
#import "MyClass.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//添加我们的测试代码
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"我是值",@"我是key1",@"我是值2",@"我是key2", nil];
//得到词典的数量
int count = [dictionary count];
NSLog(@"词典的数量为: %d",count);
//得到词典中所有KEY值
NSEnumerator * enumeratorKey = [dictionary keyEnumerator];
//快速枚举遍历所有KEY的值
for (NSObject *object in enumeratorKey) {
NSLog(@"遍历KEY的值: %@",object);
}
//得到词典中所有Value值
NSEnumerator * enumeratorValue = [dictionary objectEnumerator];
//快速枚举遍历所有Value的值
for (NSObject *object in enumeratorValue) {
NSLog(@"遍历Value的值: %@",object);
}
//通过KEY找到value
NSObject *object = [dictionary objectForKey:@"我是key2"];
if (object != nil) {
NSLog(@"通过KEY找到的value是: %@",object);
}
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
2.NSMutableDictionary是NSDictionary的子类,因此也继承其有的方法.
代码语言:javascript复制[NSMutableDictionary dictionaryWithCapacity:10];
//创建一个长度为10的字典,不过字典的内容超过了10会自动增加.
代码语言:javascript复制[NSMutableDictionary initWithCapacity: 10];
//初始化长度为10;
[dictionary setObject:~ forKey;~];
//x向可变的字典中添加数据;
[dictionary removeAllobjects];//删除所有的数据;
removeObjectForKey: //删除key的对应值;
代码语言:javascript复制#import <UIKit/UIKit.h>
#import "MyClass.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//添加我们的测试代码
//创建词典对象,初始化长度为10
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:10];
//向词典中动态添加数据
[dictionary setObject:@"被添加的value1" forKey:@"key1"];
[dictionary setObject:@"被添加的value2" forKey:@"key2"];
//通过KEY找到value
NSObject *object = [dictionary objectForKey:@"key2"];
if (object != nil) {
NSLog(@"通过KEY找到的value是: %@",object);
}
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
代码语言:javascript复制[NSMutableDictionary dictionaryWithCapacity:10];
//创建一个长度为10的字典,不过字典的内容超过了10会自动增加.