iOS 학습 노트-데이터 영구화(Plist)

2671 단어 ios
1. 모든 데이터 읽기
- (NSMutableArray *) loadAllData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       //  

    for (NSDictionary *dict in dataArray) {
        LLInfo *info = [LLInfo infoMake:[dict objectForKey:@"name"] :[dict objectForKey:@"age"]];
        [ans addObject:info];
    }
    return ans;
}

2. 데이터 삽입
- (void) insertInfo:(LLInfo *)data
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[data.name, data.age] forKeys:@[@"name", @"age"]];
    [dataArray addObject:dict];
    [dataArray writeToFile:path atomically:YES];    
}

3. 데이터 삭제
- (void) deleteInfo:(LLInfo *)data
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       //  
    
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: data.name] == 0) {
            [dataArray removeObject:dict];
            [dataArray writeToFile:path atomically:YES];
            break;
        }
    }
}

4. 교환 데이터 위치
- (void) exchangeInfo: (LLInfo *) from : (LLInfo *) to
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       //  
    int i = -1, j = -1;
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: from.name] == 0) {
            i = [dataArray indexOfObject:dict];
        }
        if ([[dict objectForKey:@"name"] compare: to.name] == 0) {
            j = [dataArray indexOfObject:dict];
        }
        if (i != -1 && j != -1) {
            break;
        }
    }
    [dataArray exchangeObjectAtIndex:i withObjectAtIndex:j];
    [dataArray writeToFile:path atomically:YES];
}

5. 데이터 수정
- (void) modifyInfo: (LLInfo *) data : (LLInfo *) newData
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: data.name] == 0) {
            [dict setValue: newData.name forKey:@"name"];
            [dict setValue: newData.age forKey:@"age"];
            [dataArray writeToFile:path atomically:YES];
            break;
        }
    }
}

좋은 웹페이지 즐겨찾기