w to Use a Dictionary in Objective-C

本文介绍了在Objective-C中如何利用字典来存储和检索数据对象,与数组相比,字典通过键值对的方式简化了数据查找过程,提高了开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://howtomakeiphoneapps.com/2009/05/how-to-use-a-dictionary-in-objective-c/

Have you ever wanted a simple way to store and retrieve your data objects?

Most programming languages have a facility to management lists of data that is indexed by keys. That is - you can store an object in a list and assign a key that could be used in the future to retrieve the data. This eliminates the need to manually move through long lists of objects to find what you are looking for.

In order to visualize this, imagine the typical Objective-C array that you create from the NSArray (or NSMutableArray) class. This array would look something like this:

Object One
Object Two
Object Three

To find something in this list you probably need to go through the entire list and do some kind of check for each object:

Is this object three? No.
Is this object three? No.
Is this object three. Yes!

That is fine, but it would be easier if you could simply use an indexed data source that would look something like this:

1Object One
2Object Two
3Object Three

Then, all you need to do is say is this: get me the object at index 3.

As long as you know what index is needed then you only need one step to get your information. The benefit may not be as obvious in the simple example using strings, but as you start to store complex objects in these data structures you will find that using dictionaries will simplify your coding life.

Without further ado - here is how you do this in Objective-C. We are doing to use the NSMutableArray class to create a dictionary.

//create the dictionary
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

//add keyed data
[dictionary setObject:@"Object One" forKey:@"1"];
[dictionary setObject:@"Object Two" forKey:@"2"];
[dictionary setObject:@"Object Three" forKey:@"3"];

//write out Object Three to the log
NSLog(@"%@", [dictionary objectForKey:@"3"]);

 

 

//release the dictionary
[dictionary release];

That is all there is too it - it is relatively painless to use a dictionary. Check out the documentation on NSDictionary to see the other built-in goodies that come with using this class.

What situations do you think you would rather use a dictionary instead of a normal array?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值