OC-字典--添加 修改 删除 查询等等

2016-01-05 20:19:00

分别有三个文件
.mian.m

int main(int argc, const char * argv[]) {

// 创建学生
Student *stu1 = [[Student alloc]initWithName:@"卞一" sex:@"男" age:@"20"];
Student *stu2 = [[Student alloc] initWithName:@"YIem" sex:@"男" age:@"20"];
Student *stu3 = [[Student alloc]initWithName:@"YI" sex:@"男" age:@"20"];
Student *stu4 = [[Student alloc]initWithName:@"Bian" sex:@"男" age:@"20"];
// 创建学生组
NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:stu1, nil];
NSMutableArray *arr2 = [NSMutableArray arrayWithObjects:stu2, stu3, nil];
NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:stu4, nil];
// 创建字典
NSMutableDictionary *contdic = [NSMutableDictionary dictionaryWithObjectsAndKeys:arr1, @"V", arr2, @"Y", arr3, @"B", nil];
// 添加联系人到匹配的分组
Student *stu5 = [[Student alloc] initWithName:@"BIanYI" sex:@"男" age:@"20"];
// 通过字典找到对应的数组
NSMutableArray *arr5 = [contdic objectForKey:@"B"];
// 将对象添加到对应数组
[arr5 addObject:stu5];
// 创建联系人/数组/Key
Student *stu6 = [[Student alloc]initWithName:@"Bianyi" sex:@"男" age:@"20"];
// 点M里方法实现 这里调用点M
[stu6 addStu:stu6 contdic:contdic];
// forin遍历字典
for (NSString *key in contdic) {
    // 通过key得到数组
    NSMutableArray *arr = [contdic objectForKey:key];
    // 遍历数组
    for (Student *stu in arr) {
        // 得到对象
        [stu info];
    }
}


NSLog(@"%@", contdic.allKeys);
return 0;

}


.Student.h

// 自定义方法

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, copy) NSString *age;
// 初始化

  • (instancetype)initWithName:(NSString *)name

                         sex:(NSString *)sex
                         age:(NSString *)age;
    
  • (void)info;
    // 添加/修改学生信息
  • (void)addStu:(Student )stu contdic:(NSMutableDictionary )contdic;

.Student.m

// 
  • (instancetype)initWithName:(NSString *)name

                     sex:(NSString *)sex
                     age:(NSString *)age

    {
    self = [super init];
    if (self) {

    self.name = name;
    self.sex = sex;
    self.age = age;

    }
    return self;
    }

//

  • (void)info
    {

    NSLog(@"%@- %@- %@-", self.name, self.sex, self.age);

    }

// 创建/添加/修改学生信息

  • (void)addStu:(Student )stu contdic:(NSMutableDictionary )contdic
    {
    // 判断输入参数是否合法
    if (0 == stu.name.length || 0 == stu.sex.length) {

    NSLog(@"参数是否合法");
    return;

    }
    // 截取第一个首字母作为key
    NSString *str = [stu.name substringFromIndex:1];
    // str - key
    NSMutableArray *arrTemp = [contdic objectForKey:str];
    if (nil == arrTemp) {

    // 创建数组
    arrTemp = [NSMutableArray array];
    // 将数组添加进字典
    [contdic setObject:arrTemp forKey:@"N"];
    

    }
    // 将对象添加进数组
    [arrTemp addObject:stu];
    }


当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »