• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
yif
专注于C/C++,C#,Objective-C,GIS,空间统计,数据挖掘,智慧城市
博客园    首页    新随笔    联系   管理    订阅  订阅
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一次
}

 

posted on 2015-12-24 15:37  mattran  阅读(137)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3