iOS 登录账号保存

497F6E8E-1842-4492-848E-7B9B0F1659EF.png
    NSMutableArray *accArr = [NSMutableArray array];
    NSArray *ontMBYArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"accountpwd"];
    [accArr addObjectsFromArray:ontMBYArr];//将不可变的添加到可变数组中
    if (ontMBYArr == nil || [ontMBYArr isKindOfClass:[NSNull class]] || ontMBYArr.count == 0) {
        
        NSMutableDictionary *accDic = [NSMutableDictionary dictionary];
        [accDic setObject:MBYPhone forKey:@"account"];
        [accDic setObject:MBYPassword forKey:@"pwd"];
        [accArr addObject:accDic];
        
    } else {
        
        __block BOOL newAccount = YES;//记录是否是新账号
        [accArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"account"] isEqualToString: account]) {//判断账号是否相同
                //更新数据位置
                [accArr removeObjectAtIndex:idx];
                [accArr insertObject:obj atIndex:0];
                newAccount = NO;
                *stop = YES;
            }
        }];
        
        if (newAccount) {
            //新的数据
            NSMutableDictionary *accDic = [NSMutableDictionary dictionary];
            [accDic setObject:MBYPhone forKey:@"account"];
            [accDic setObject:MBYPassword forKey:@"pwd"];
            //新账号插到第一位
            [accArr insertObject:accDic atIndex:0];
        }
        
    }
    //将数组保存本地
    [[NSUserDefaults standardUserDefaults] setObject:accArr forKey:@"accountpwd"];
    [[NSUserDefaults standardUserDefaults] synchronize];

你可能感兴趣的:(iOS 登录账号保存)