@interface DataManager ()

@property (nonatomic, strong) NSMutableArray *musicArray;

@end

@implementation DataManager

static DataManager *dataManager = nil;

+ (DataManager *)sharedManager{
    @synchronized(self) {
        
        if (dataManager == nil) {
            dataManager = [DataManager new];
        }
        return dataManager;
    }
}

//+ (DataManager *)sharedManager{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        dataManager = [DataManager new];
//    });
//}

// 重写init方法,这种方法会在调用init方法中多次解析数据发送网络请求,造成流量和内存的浪费
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self requestData];
    }
    return self;
}


- (void)requestData{
    // 转到子线程,不然在主线程时造成程序假死
    dispatch_async(dispatch_get_global_queue(0, 0),  ^{
        
        // 请求数据
        // 这种解析方式会把数据一次性解析完,实际开发中是不会这么实现的
        NSArray *dataArray = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:kMusicList]];
        
        for (int i  = 0; i < dataArray.count; i++) {
            NSLog(@"%@", dataArray[i]);
            // 创建Model
            MusicModel *model = [MusicModel new];
            [model setValuesForKeysWithDictionary:dataArray[i]];
            [self.musicArray addObject:model];
        }
        // 返回主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!self.myUpDataUI) {
                NSLog(@"block 没有代码");
            }else{
                self.myUpDataUI();
            }
        });
    });
    
//    for (NSDictionary *dic in dataArray) {
//        NSLog(@"%@", dic);
//    }
}

#pragma mark -- lazy load
- (NSMutableArray *)musicArray{
    if (!_musicArray) {
        _musicArray = [NSMutableArray new];
    }
    return _musicArray;
}


// 重写get方法桥接起来
- (NSArray *)allMusic{
    return self.musicArray;
}

- (MusicModel *)musicModelWithIndex:(NSInteger)index{
    MusicModel *model = _musicArray[index];
    return model;
}

@end
