标签:
字典就是关键字及其定义(描述)的集合。Cocoa中的实现字典的集合NSDictionary在给定的关键字(通常是一个NSString)下存储一个数值(可以是任何类型的对象)。然后你就可以用这个关键字来查找相应的数值。
不同于数组,字典(也被称为散列表或关联数组)使用的是键查询的优化存储方式。它可以立即找出要查询的数据,而不需要遍历整个数组进行查找。
可使用dictionaryWithObjectsAndKeys来创建字典
查询字典的值:objectForKey
NSMutableDictionary的dictionary方法可以创建一个可变字典,也可以使用dictionaryWithCapaticy:。
使用 setObject:forkey: 方法添加字典元素,如果关键字已存在,则用新植替换旧值。
类似的,NSMutableDictionary类允许随意添加或删除字典元素。
添加元素:setObject:forkey:
删除元素:removeObjectForKey:
#import <Foundation/Foundation.h> @interface MyClass : NSObject { NSString *firstName; NSString *lastName; } -(void) setFirstName:(NSString*)m_firstName; -(NSString*)firstName; -(void) setLastName:(NSString*)m_lastName; -(NSString*)lastName; @end
// // MyClass.m // Dictionary // // Created by Aron-Mac-VM on 3/14/16. // Copyright (c) 2016 PQLabs. All rights reserved. // #import "MyClass.h" @implementation MyClass -(void)setFirstName:(NSString *)m_firstName { firstName = m_firstName; } -(NSString*)firstName { return firstName; } -(void)setLastName:(NSString *)m_lastName { lastName = m_lastName; } -(NSString*)lastName { return lastName; } -(NSString*)description { if(firstName == nil || lastName == nil) { return @"No Name found."; } else { return [NSString stringWithFormat:@"%@ %@",firstName,lastName]; } } @end
// // main.m // Dictionary // // Created by Aron-Mac-VM on 3/14/16. // Copyright (c) 2016 PQLabs. All rights reserved. // #import <Foundation/Foundation.h> #import "MyClass.h" int main(int argc, const char * argv[]) { @autoreleasepool { MyClass *my1 = [MyClass new]; MyClass *my2 = [[MyClass alloc]init]; MyClass *my3 = [MyClass new]; MyClass *my4 = [MyClass new]; NSDictionary *myClassDict; myClassDict = [NSDictionary dictionaryWithObjectsAndKeys:my1, @"my1", my2, @"my2", my3, @"my3", my4, @"my4",nil]; //获取值objectForkey MyClass *sub = [myClassDict objectForKey:@"my3"]; if(sub==nil) { exit(1); } [sub setFirstName:@"pan"]; [sub setLastName:@"Sunde"]; NSLog(@"mofiy the data: %@",sub); //遍历字典 for(id key in myClassDict) { NSLog(@"key: %@, value: %@",key,[myClassDict objectForKey:key]); } //添加新元素 //NSDictionary无法添加或者删除元素,可以使用NSMutableDictionary NSMutableDictionary *myNewDict = [NSMutableDictionary dictionary]; //把原有的字典添加到新字典的一对元素 [myNewDict setObject:myClassDict forKey:@"旧的不可变字典myClassDict"]; //遍历添加已有数据(原字典) for(id key in myClassDict) { [myNewDict setObject:[myClassDict objectForKey:key] forKey:key]; } NSString *newValue = @"This is a new Value"; NSString *newKey = @"a new Key"; [myNewDict setObject:newValue forKey:newKey]; //遍历myNewDict NSLog(@"*********遍历字典myNewDict如下:"); for(id key in myNewDict) { NSLog(@"Key: %@, value: %@",key,[myNewDict objectForKey:key]); } NSLog(@"*********遍历字典myNewDict Over:"); //删除元素 [myNewDict removeObjectForKey:@"a new Key"]; for(id key in myNewDict ) { NSLog(@"key: %@,value: %@",key,[myNewDict objectForKey:key]); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/mypsq/p/5276307.html