1. 이전 포스팅 확인하기

 

https://growingsaja.tistory.com/913

 

 

 

 

 

2. jsonFileRead 기능 소스코드 수정 전 : 싱글톤 적용 전

 

// vim CRTJSONReader.h

#import <Foundation/Foundation.h>

@interface CRTJSONReader : NSDictionary

// JSON 파일을 읽어오기 위한 메소드 선언
- (NSDictionary*)loadJSONFromFile:(NSString *)fileName;

@end

 

// vim CRTJSONReader.m

#import "CRTJSONReader.h"

@implementation CRTJSONReader

- (NSDictionary *) loadJSONFromFile:(NSString *)jsonFileName {
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *jsonFilePath = [mainBundle pathForResource:jsonFileName ofType:@"json"];
    NSError *errorJson = nil;
    // 불러올 객체 없을때 reutrn하는 데이터 생성
    NSDictionary *emptyDictionary = [NSDictionary dictionary];

    // 파일 경로를 확인합니다.
    if (jsonFilePath != nil) {
        NSLog(@"JSON 파일 경로: %@", jsonFilePath);

        // JSON 데이터를 읽어옵니다.
        NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];

        // JSON을 NSDictionary로 파싱합니다.
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&errorJson];
        if (errorJson) {
            NSLog(@"JSON 파싱 오류: %@", [errorJson localizedDescription]);
            return emptyDictionary;
        } else {
            // JSON 데이터를 사용합니다.
//            NSLog(@"JSON 객체: %@", jsonObject);
            return jsonObject;
        }
    } else {
        NSLog(@"JSON 파일을 찾을 수 없습니다.");
        return emptyDictionary;
    }
}

@end

 

 

 

 

 

3. jsonFileRead 기능 소스코드 수정 후 : 싱글톤 적용 후

 

// vim CRTJSONReader.h

#import <Foundation/Foundation.h>

@interface CRTJSONReader : NSDictionary

@property (readwrite, strong, nonatomic) NSDictionary *loadData;

// JSON 파일을 읽어오기 위한 메소드 선언
+(instancetype)sharedInstance;
-(void)tryReadJsonFile:(NSString *)fileName;

@end

 

// vim CRTJSONReader.m

#import "CRTJSONReader.h"

@implementation CRTJSONReader

+(instancetype)sharedInstance {
    
    static CRTJSONReader *sharedInstance = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void) tryReadJsonFile:(NSString *)jsonFileName {
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSArray *separatedJsonFileName = [jsonFileName componentsSeparatedByString:@"."];
    NSString *fileExtension = [separatedJsonFileName objectAtIndex:separatedJsonFileName.count-1];
    if ([fileExtension isEqual:@"json"]) {
        // 읽으려는 파일이 json인지 확인
        // file 확장명 길이 + 1을 해서, .까지 포함한 string 제거
        NSUInteger lengthToKeep = [jsonFileName length] - (fileExtension.length + 1);
        NSString *jsonFilePath = [mainBundle pathForResource:[jsonFileName substringToIndex:lengthToKeep] ofType:fileExtension];
        [self executeReadJsonFilePath:jsonFilePath];
    } else {
        NSLog(@"[WARN] You Need To Try Reading Json File.");
        _loadData = @{};
    }
}
-(void) executeReadJsonFilePath:(NSString *)jsonFilePath {
    NSError *errorJson = nil;
    // 파일 경로를 확인합니다.
    if (jsonFilePath != nil) {
        // JSON 데이터를 읽어옵니다.
        NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];

        // JSON을 NSDictionary로 파싱합니다.
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&errorJson];
        if (errorJson) {
            NSLog(@"[ERROR] JSON Parsing Error : %@", [errorJson localizedDescription]);
            _loadData = @{};
        } else {
            // JSON 데이터를 사용합니다.
//            NSLog(@"JSON 객체: %@", jsonObject);
            NSLog(@"[SUCCESS] Load File Path : %@", jsonFilePath);
            _loadData = jsonObject;
        }
    } else {
        NSLog(@"[ERROR] Json File Is Not Exist.");
        _loadData = @{};
    }
}

@end

 

 

 

 

 

4. DateTime 파일 수정

 

기존 CRTDateTime을 DateTime으로 변경 적용 및 싱글톤 적용으로 수정

 

//vim DateTime.h

@interface DateTime : NSObject

@property (readwrite, strong, nonatomic) NSString *dateTime;
@property (readwrite, strong, nonatomic) NSDateFormatter *dateFormatter;

+(instancetype)sharedInstance;

-(void)NowUTC: (NSString *)format;
-(void)NowKST: (NSString *)format;

@end

 

// vim DateTime.m

#import <Foundation/Foundation.h>
#import "DateTime.h"

@implementation DateTime

+(instancetype)sharedInstance {
    
    static DateTime *sharedInstance = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        sharedInstance = [[self alloc] init];
        // [날짜 형식 포맷 + UTC 세팅 :: 24시간 형태]
        sharedInstance.dateFormatter = [[NSDateFormatter alloc] init];
    });
    return sharedInstance;
}

-(void)NowUTC: (NSString *)format {
    // [현재 UTC 날짜 얻어 오기]
    NSDate *nowUTCDateRaw = [NSDate date];
    
    // format 적용
    [_dateFormatter setDateFormat:format];
    
    NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [_dateFormatter setTimeZone:utcTimeZone];
    
    // [현재 UTC 일시 저장]
    _dateTime = [_dateFormatter stringFromDate:nowUTCDateRaw];
}

-(void)NowKST: (NSString *)format {
    // [현재 UTC 날짜 얻어 오기]
    NSDate *nowUTCDateRaw = [NSDate date];
    
    // format 적용
    [_dateFormatter setDateFormat:format];
    
    NSTimeZone *kstTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Seoul"];
    [_dateFormatter setTimeZone:kstTimeZone];
    
    // [현재 KST 일시 출력]
    _dateTime = [_dateFormatter stringFromDate:nowUTCDateRaw];
}




@end

 

 

 

 

 

5. DateTime 사용하는 소스코드 주요 수정사항

 

// 현재 시간 확인을 위한 singlton instance 생성
    DateTime *now = [DateTime sharedInstance];
    // 레이블의 텍스트를 설정합니다. 여기에서는 UTC 시간을 업데이트합니다.
    [now NowUTC: @"yyyy-MM-dd (E) HH:mm:ss"];
    self.liveUTCLabel.text = now.dateTime;
    // 레이블의 텍스트를 설정합니다. 여기에서는 KST 시간을 업데이트합니다.
    [now NowKST: @"yyyy-MM-dd (E) HH:mm:ss"];
    self.liveKSTLabel.text = now.dateTime;

 

 

 

 

 

 

+ Recent posts