2013-04-28 2 views
1

나는 여러 해 동안이 문제에 어려움을 겪어 왔으며 여기에 도움이 필요하다. :) 나는 꽤 큰 JSON을 appdelegate의 didFinishLaunchingWithOptions으로 구문 분석하는 앱을 가지고있다.데이터를 앱에 로컬로 저장하는 방법은 무엇입니까?

내 모델 개체는 다음과 같습니다

탭 :

NSString *title 
NSMutableArray *categories 

카테고리 :

NSString *title 
NSMutableArray *items 

항목 내가 구문 분석의 원인, 로컬로 데이터를 저장해야

NSString *title 
NSString *description 
UIImage *image 

약 15 초 걸린다. 내 앱이 시작될 때마다 실행됩니다. SBJSON 프레임 워크를 사용하고 있습니다.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"json_template" ofType:@"json"]; 

    NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil]; 
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init]; 
    NSMutableDictionary *json = [jsonParser objectWithString: contents]; 
    tabs = [[NSMutableArray alloc] init]; 
    jsonParser = nil; 

    for (NSString *tab in json) 
    { 
     Tab *tabObj = [[Tab alloc] init]; 
     tabObj.title = tab; 

     NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0]; 
     for (NSString *key in categoryDict) 
     { 

      Category *catObj = [[Category alloc] init]; 
      catObj.name = key; 


      NSArray *items = [categoryDict objectForKey:key]; 

      for (NSDictionary *dict in items) 
      { 
       Item *item = [[Item alloc] init]; 
       item.title = [dict objectForKey: @"title"]; 
       item.desc = [dict objectForKey: @"description"]; 
       item.url = [dict objectForKey: @"url"]; 
       if([dict objectForKey: @"image"] != [NSNull null]) 
       { 
        NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: @"image"]]; 
        NSData *imageData = [NSData dataWithContentsOfURL: imgUrl]; 
        item.image = [UIImage imageWithData: imageData]; 
       } 
       else 
       { 
        UIImage *image = [UIImage imageNamed: @"standard.png"]; 
        item.image = image; 
       } 

       [catObj.items addObject: item]; 
      } 
      [tabObj.categories addObject: catObj]; 
     } 
     [tabs addObject: tabObj]; 
    } 

이 일을하는 가장 좋은 방법은 무엇입니까 :

여기 구문 분석에 대한 내 코드입니까? 핵심 데이터 또는 NSFileManager을 사용하십니까? som 코드 예제가 너무 있으면 나를 행복하게 만들 것입니다. 앱이 앱 스토어를 준비하기 전에 해결해야 할 마지막 사항입니다. 나는이 문제를 해결할 수 없다.

+1

? 5KB? 10MB? 1GB? – rekire

+0

코드에 [Xcode instruments] (http://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/Introduction.html)를 실행하는 것을 고려한 적이 있습니까? 필자는 구문 분석에서 물건을 극적으로 느리게 만들 것이라고 생각합니다 (예 : 동기식 "NSData dataWithContentsOfURL'"호출). –

+0

86 KB 지금입니다. – Jojo

답변

2

iOS에서 작업하는 경우 파일을 문서 폴더에 저장합니다. Mac OS X에서는 응용 프로그램 지원 폴더에 있습니다. iOS를 사용 중이므로 this answer을 읽고 문서 폴더에 액세스하는 방법을 읽어보십시오.

저장하려는 모든 개체에 NSCoding을 구현해야합니다. 위의 변수가 이미 있습니다. 탭, 카테고리 및 항목을 직접 저장해야 NSCoding을 구현해야합니다. 그런 다음 파일에 직렬화하면됩니다. 앱을 열 때이 파일을 찾아 파싱하지 않고 개체를 다시 가져올 수 있습니다.

같은 것을 보일 것입니다 코드 (테스트되지 않은 및 오류 검사는 간결 ommited됩니다) :

당신을 위해 큰 조용 무엇
- (void) saveStateToDocumentNamed:(NSString*)docName 
{ 
    NSError  *error; 
    NSFileManager *fileMan = [NSFileManager defaultManager]; 
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString  *docPath = [paths[0] stringByAppendingPathComponent:docName]; 

    if ([fileMan fileExistsAtPath:docPath]) 
     [fileMan removeItemAtPath:docPath error:&error]; 

    // Create the dictionary with all the stuff you want to store locally 
    NSDictionary *state = @{ ... }; 

    // There are many ways to write the state to a file. This is the simplest 
    // but lacks error checking and recovery options. 
    [NSKeyedArchiver archiveRootObject:state toFile:docPath]; 
} 

- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName 
{ 
    NSError  *error; 
    NSFileManager *fileMan = [NSFileManager defaultManager]; 
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString  *docPath = [paths[0] stringByAppendingPathComponent:docName]; 

    if ([fileMan fileExistsAtPath:docPath]) 
     return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath]; 

    return nil; 
}