2014-09-26 3 views
0

У меня есть три таблицы, один ко многим отношений между сессии и альбом, один ко многим отношений между альбомом песни, когда я попытался не извлекать данные из песен Тогда я ничегоИзвлечение данных в основных данных

Вот мой readFRomDB функ

- (недействительными) readDataFromDB {

AppDelegate *delegates = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 
self.managedObjectContext = [delegates managedObjectContext]; 

if (runningSessionArray.count > 0) { 
    [runningSessionArray removeAllObjects]; 
} 

NSManagedObjectContext *moc = [self managedObjectContext]; 
NSArray *searchResults = nil; 
NSArray *searchAlbumsResults = nil; 
NSArray *searchSongsResult=nil; 


NSFetchRequest * fetchRequest1 = [[NSFetchRequest alloc] init]; 
NSFetchRequest * fetchRequest2 = [[NSFetchRequest alloc] init]; 

NSEntityDescription *entityDescription = [NSEntityDescription 

              entityForName:@"RunningSession" inManagedObjectContext:moc]; 




NSFetchRequest *requestData = [[NSFetchRequest alloc] init]; 
[requestData setEntity:entityDescription]; 
[requestData setFetchLimit:1] ; 


NSError *error; 
// if get a entity, that means exists, so fetch it. 


searchResults = [managedObjectContext executeFetchRequest:requestData error:&error]; 



for (RunningSession *session in searchResults) { 
    // Update the Records 
    self.runnningSessionId=[NSString stringWithFormat:@"%@",session.runningSessionID]; 
    self.title=session.title; 
    self.desc=[NSString stringWithFormat:@"%@",session.desc]; 


    [fetchRequest1 setEntity:[NSEntityDescription entityForName:@"Albums" 
             inManagedObjectContext:session.managedObjectContext]]; 
    [fetchRequest1 setEntity:entityDescription]; 
    [fetchRequest1 setFetchLimit:1] ; 

    searchAlbumsResults = [session.managedObjectContext executeFetchRequest:fetchRequest1 error:&error]; 




    NSMutableArray *tagNamesArray = [[NSMutableArray alloc] init]; 
    //NSLog(@"Local Discount Shops:%@",discounts.shops); 
    NSSet *tagA = session.albums; 
    if (tagA.count>0) { 





     for (Albums *tag in tagA 
      ) { 
      // NSLog(@"tag:%@",tag); 
      NSString *albumID; 
      NSString *aTitle; 
      NSString *aPrice; 
      NSString *aDuration; 
      NSString *aUrl; 
      NSString *aPurchasedHtml; 
      NSString *aNonPurchasedHtml; 



      if (tag.albumID != NULL) { 
       albumID = [NSString stringWithFormat:@"%@",tag.albumID]; //tag.shopId; 
      }else{ 
       albumID = @""; 
      } 
      if (tag.title != NULL) { 
       aTitle = tag.title; 
      } 
      else{ 
       aTitle = @""; 
      } 
      if (tag.price != NULL) { 
       aPrice = tag.price; 
      } 
      else{ 
       aPrice = @""; 
      } 


      if (tag.duration != NULL) { 
       aDuration = tag.duration; 
      } 
      else{ 
       aDuration = @""; 
      } 
      if (tag.url != NULL) { 
       aUrl = tag.url; 
      } 
      else{ 
       aUrl = @""; 
      } 
      if (tag.purchasedHtml != NULL) { 
       aPurchasedHtml = tag.purchasedHtml; 
      } 
      else{ 
       aPurchasedHtml = @""; 
      } 
      if (tag.nonPurchasedHtml != NULL) { 
       aNonPurchasedHtml = tag.nonPurchasedHtml; 
      } 
      else{ 
       aNonPurchasedHtml = @""; 
      } 

      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:albumID,@"Id",aTitle,@"Title",aPrice,@"Price", aDuration,@"Duration", 
            albumUrl,@"Url",aPurchasedHtml,@"PurchasedItemsHtml",aNonPurchasedHtml,@"NonPurchasedItemsHtml", nil]; 

      [tagNamesArray addObject:dict]; 




      NSLog(@"tag.shop:%@",tag.songs); 




      [fetchRequest2 setEntity:[NSEntityDescription entityForName:@"Songs" 
               inManagedObjectContext:tag.managedObjectContext]]; 
      [fetchRequest2 setEntity:entityDescription]; 
      [fetchRequest2 setFetchLimit:1]; 
      searchSongsResult = [tag.managedObjectContext executeFetchRequest:fetchRequest2 error:&error]; 




      NSMutableArray *songsNamesArray = [[NSMutableArray alloc] init]; 
      //NSLog(@"Local Discount Shops:%@",discounts.shops); 
      NSSet *tags = tag.songs; 


      if (tags.count>0) { 

      for (Songs *tag in tags) { 
       // NSLog(@"tag:%@",tag); 
       NSString *sID; 
       NSString *sTitle; 
       NSString *startTime; 


       if (tag.songsId !=NULL) { 
        sID = [NSString stringWithFormat:@"%@",tag.songsId]; //tag.shopId; 
       }else{ 
        sID = @""; 
       } 
       if (tag.title != NULL) { 
        sTitle = tag.title; 
       } 
       else{ 
        sTitle = @""; 
       } 
       if (tag.startTime != NULL) { 
        startTime = tag.startTime; 
       } 
       else{ 
        startTime = @""; 
       } 


       NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:sID,@"Id",sTitle,@"Title",startTime,@"Duration", nil]; 

       [songsNamesArray addObject:dict]; 

      } 





      } 



      NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:albumID,@"Id",albumTitle,@"Title",albumPrice,@"Price",albumDuration,@"Duration",albumUrl,@"Url",albumPurchasedHtml,@"PurchasedItemsHtml",albumNonPurchasedHtml,@"NonPurchasedItemsHtml",songsNamesArray,@"Songs", nil]; 
     } 


    } 
    // NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:@"firstName = 'Bob'"]; 
    //  NSLog(@"Bobs: %@", [discounts filteredArrayUsingPredicate:bobPredicate]); 

    NSMutableArray *albumArray = [[NSMutableArray alloc] init]; 
    albumArray = [tagNamesArray mutableCopy]; 


    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:self.runnningSessionId,@"Id",title,@"Title",self.title,@"title",self.desc,@"Description",albumArray,@"Albums", nil]; 


    [self.runningSessionArray addObject:dict]; 
    //  [self StudentDiscountData]; 
    // NSLog(@"studentDataArray:%@",self.studentDataArray); 


} 

NSLog(@"RunningSession: %@",self.runningSessionArray); 

}

ответ

0

Я думаю, что вам не нужно всех этих шагов получения данных сеанса достаточно и от того, что вы можете получить список альбомов, когда вы устанавливаете отношения друг к другу. И из каждого альбома вы получите Песни

AppDelegate *delegates = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 
self.managedObjectContext = [delegates managedObjectContext]; 

if (runningSessionArray.count > 0) { 
    [runningSessionArray removeAllObjects]; 
} 

NSManagedObjectContext *moc = [self managedObjectContext]; 
NSArray *searchResults = nil; 
NSArray *searchAlbumsResults = nil;// not required 
NSArray *searchSongsResult=nil;//not required 


NSFetchRequest * fetchRequest1 = [[NSFetchRequest alloc] init];//not required 
NSFetchRequest * fetchRequest2 = [[NSFetchRequest alloc] init];//not required 

NSEntityDescription *entityDescription = [NSEntityDescription 

             entityForName:@"RunningSession" inManagedObjectContext:moc]; 




NSFetchRequest *requestData = [[NSFetchRequest alloc] init]; 
[requestData setEntity:entityDescription]; 
[requestData setFetchLimit:1] ; 


NSError *error; 
// if get a entity, that means exists, so fetch it. 


searchResults = [managedObjectContext executeFetchRequest:requestData error:&error]; 
//This returns array of sessions 

for (RunningSession *session in searchResults) { 

    NSArray *albumsArray = session.albums; //This returns Albums list as you set one to many relation 
    for (Album *album in albumsArray) { 
    NSArray *songsArray = album.songs; //This returns songs list as you set one to many relation 
    } 
} 
+0

Спасибо за ваш быстрый ответ! Я получаю список песен и альбомов сейчас, но у меня есть одна проблема при разборе их в формате словаря. Как я могу получить количество песен и альбомов, но не могу получить там идентификатор названия и т. Д. –

+0

Среднее я хочу сохранить точный в том же формате в котором я получаю от JSON до myarray и Dic, так что я могу получить один единственный массив, содержащий словарь, каждый индекс, такой как JSON. –

+0

Потому что, когда мы добавляем эту строку NSArray * albumsArray = session.albums; получаем предупреждение, потому что session.album - NSSET, а albumArray - массив. –

Смежные вопросы