ios developer tiny share-20161025

本文详细介绍了Objective-C中字典(NSDictionary)的概念及其使用方法。字典通过键值对存储对象,通常使用字符串作为键。文章还展示了如何通过分配初始化及类工厂方法创建字典,并提供了字面量语法的例子。

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

今天讲Objective-C的字典NSDictionary。


Dictionaries Collect Key-Value Pairs
Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

It’s best practice to use string objects as dictionary keys, as shown in Figure 6-3.

Figure 6-3  A Dictionary of Objects


Note: It’s possible to use other objects as keys, but it’s important to note that each key is copied for use by a dictionary and so must support NSCopying.
If you wish to be able to use Key-Value Coding, however, as described in Key-Value Coding Programming Guide, you must use string keys for dictionary objects.


Creating Dictionaries

You can create dictionaries using either allocation and initialization, or class factory methods, like this:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
			   someObject, @"anObject",
		 @"Hello, World!", @"helloString",
					  @42, @"magicNumber",
				someValue, @"aValue",
						 nil];

Note that for the dictionaryWithObjectsAndKeys: and initWithObjectsAndKeys: methods, each object is specified before its key, and again, the list of objects and keys must be nil-terminated.


Literal Syntax


Objective-C also offers a literal syntax for dictionary creation, like this:

NSDictionary *dictionary = @{
			  @"anObject" : someObject,
		   @"helloString" : @"Hello, World!",
		   @"magicNumber" : @42,
				@"aValue" : someValue
};
Note that for dictionary literals, the key is specified before its object and is not nil-terminated.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值