Objective-C:Foundation框架-常用类-NSMutableDictionary

 直接上代码吧:

#import <Foundation/Foundation.h>

@interface Student : NSObject
@property (nonatomic, retain) NSString *name;

+ (id)studentWithName:(NSString *)name;
@end

#import "Student.h"

@implementation Student

+ (id)studentWithName:(NSString *)name {
    Student *stu = [[Student alloc] init];
    stu.name = name;
    return [stu autorelease];
}

- (void)dealloc {
    NSLog(@"%@被销毁了", _name);
    // 释放name
    [_name release];
    [super dealloc];
}
@end

 

#import <Foundation/Foundation.h>
#import "Student.h"

#pragma mark 可变字典的使用
void dictUse() {
    // 创建一个空的字典
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    Student *stu1 = [Student studentWithName:@"stu1"];
    Student *stu2= [Student studentWithName:@"stu2"];
    
    // 添加元素
    // stu1的计数器会+1
    [dict setObject:stu1 forKey:@"k1"];
    NSLog(@"stu1:%zi", [stu1 retainCount]);
    
    // 添加其他字典other到当前字典dict中
    NSDictionary *other = [NSDictionary dictionaryWithObject:@"v2" forKey:@"k2"];
    [dict addEntriesFromDictionary:other];
    
    // 删除所有的键值对
    // [dict removeAllObjects];
    
    // 删除k1对应的元素stu1,stu1会做一次release操作
    [dict removeObjectForKey:@"k1"];
    NSLog(@"stu1:%zi", [stu1 retainCount]);
    
    // 删除多个key对应的value
    // [dict removeObjectsForKeys:[NSArray arrayWithObject:@"k1"]];
    
    // 字典被销毁时,内部的所有key和value计数器都会-1,也就是说stu1会release一次
}

 

转载于:https://www.cnblogs.com/yif1991/p/5068224.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值