年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1869|回复: 0

可变字典的基本使用,及字典的遍历

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-3-23 23:51:16 | 显示全部楼层 |阅读模式
    1. //
    2. //  main.m
    3. //  NSMutableDictionary
    4. //
    5. //  Created by yusian on 14-3-23.
    6. //  Copyright (c) 2014年 小龙虾论坛. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. int main()
    10. {
    11.     // 创建一个可变字典
    12.     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    13.    
    14.     // 添加键值对
    15.     [dict setObject:@"yusian" forKey:@"name"];
    16.    
    17.     [dict setObject:@"ChangSha" forKey:@"address"];
    18.    
    19.     // 移除键值对
    20.     // [dict removeObjectForKey:(id)];
    21.     // [dict removeAllObjects];
    22.     // [dict removeObjectsForKeys:(NSArray *)];
    23.    
    24.     // 字典打印
    25.     NSLog(@"%@", dict);
    26.    
    27.     // 字典的遍历之for循环
    28.     for (int i = 0; i < dict.count; i++) {
    29.    
    30.         // 先取出所有的key
    31.         NSArray * keys = [dict allKeys];
    32.         
    33.         // 每次循环都从数组中取出一个key值
    34.         NSString *key = keys[i];
    35.         
    36.         // 根据每次取出的key值,找到对应的键值
    37.         NSString *obj = dict[key];
    38.         
    39.         // 输出
    40.         NSLog(@"%@ - %@", key, obj);
    41.     }
    42.    
    43.     // 字典遍历之遍历方法(传block方式),具体实现在数组的遍历方法中有详细研究过
    44.     [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    45.         
    46.         // 可直接使用key与obj
    47.         NSLog(@"%@ - %@", key, obj);
    48.         
    49.         // 如果key值等于name则遍历终止
    50.         if ([key isEqualToString:@"name"]) {
    51.             
    52.             *stop = YES;
    53.             
    54.         }
    55.     }];
    56.     return 0;
    57. }
    复制代码

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-5 16:32 , Processed in 0.044092 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表