1. 程式人生 > >objective-c 中數據類型之四 字典(NSDictionary)

objective-c 中數據類型之四 字典(NSDictionary)

bject ted ray 初始化 -c lec com lock led

// 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)