首页 > 代码库 > objective-c 中数据类型之四 字典(NSDictionary)

objective-c 中数据类型之四 字典(NSDictionary)

// 1. 字典初始化、赋值方式1
    NSMutableDictionary *m_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    [m_dictionary setObject:@1 forKey:@"语文"];
    [m_dictionary setObject:@2 forKey:@"数学"];
    [m_dictionary setObject:@3 forKey:@"英语"];
    // 字典初始化、赋值方式2
    NSDictionary *dict1 = @{@"语文": @1, @"数学": @2, @"英语": @3};
    m_dictionary = [NSMutableDictionary dictionaryWithDictionary:dict1];
    
    // 字典初始化、赋值方式3
    m_dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys: @1, @"语文", @2, @"数学", @3, @"英语", nil];
    // 字典初始化、赋值方式4
    m_dictionary = [NSMutableDictionary dictionaryWithObjects:@[@1, @2, @3] forKeys:@[@"语文", @"数学", @"英语"]];
    // 赋值方式5
    NSDictionary *dict2 = @{ @"物理": @4};
    [m_dictionary addEntriesFromDictionary:dict2];
    
    // 2. 排序 方式1
    NSArray *sortedKeysArray =
    [m_dictionary keysSortedByValueUsingSelector:@selector(compare:)];
    // sortedKeysArray (语文, 数学, 英语, 物理)
    // 方式2
    NSArray *blockSortedKeys = [m_dictionary keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    // blockSortedKeys (语文, 数学, 英语, 物理)

objective-c 中数据类型之四 字典(NSDictionary)