NSMutableDictionary类

作者:追风剑情 发布于:2019-3-2 10:47 分类:Objective-C

NSMutableDictionary是可变词典。
NSMutableDictionary是NSDictionary的子类。

常用的NSMutableDictionary方法
方法 描述
+(instancetype) dictionaryWithCapacity: size 使用一个初始指定的size创建可变词典
-(instancetype) initWithCapacity: size 将新分配的词典初始化为指定的size
-(void) removeAllObjects     删除词典中所有记录
-(void) removeObjectForKey: key 删除词典中指定key对应的记录
-(void) setObject: obj forKey: key 向词典为key的键添加obj,如果key已存在,则替换该值

说明:
表中的key、key1、key2、obj、obj1和obj2是任意对象,size是一个NSUInteger无符号整数。

示例

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 创建一个空的可变词典, 注意:key不能为nil
        NSMutableDictionary *glossary = [NSMutableDictionary dictionary];
        
        // 存储3个条目在类别中
        /*
        [glossary setObject: @"A class defined so other classes can inherit from it"
                     forKey: @"abstract class"];
        
        [glossary setObject: @"To implement all the methods defined in a protocol"
                     forKey: @"adopt"];
        
        [glossary setObject: @"Storing an object for later use"
                     forKey: @"archiving"];
         */
        // 与上面的语法等价
        glossary[@"abstract class"] = @"A class defined so other classes can inherit from it";
        glossary[@"adopt"] = @"To implement all the methods defined in a protocol";
        glossary[@"archiving"] = @"Storing an object for later use";
        
        // 检索并显示它们
        /*
        NSLog(@"abstract class: %@", [glossary objectForKey: @"abstract class"]);
        NSLog(@"adopt: %@", [glossary objectForKey: @"adopt"]);
        NSLog(@"archiving: %@", [glossary objectForKey: @"archiving"]);
         */
        // 与上面的语法等价
        NSLog(@"abstract class: %@", glossary[@"abstract class"]);
        NSLog(@"adopt: %@", glossary[@"adopt"]);
        NSLog(@"archiving: %@", glossary[@"archiving"]);
    }
    return 0;
}

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号