2016-07-24 2 views
0

У меня проблема с tableView, CoreData и JSON. И я не знаю, что делать дальше. Я пытаюсь сделать это:Tableview, основные данные и JSON в Objective C

This is what I'm trying to do

This is what I need to do Проблема заключается в моем TableView просто показывает первый объект, и мне нужно, чтобы показать все. Является JSON:

{ 
    "status":"OK", 
    "groups":[ 
     { 
     "group_name":"Group 1", 
     "group_id":1, 
     "group_status":"FINISHED", 
     "group_is_active":"YES", 
     "group_students":[ 
      { 
       "student_name":"Student 1", 
       "student_id":1, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 1" 
      }, 
      { 
       "student_name":"Student 2", 
       "student_id":2, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 2" 
      }, 
      { 
       "student_name":"Student 3", 
       "student_id":3, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 3" 
      }, 
      { 
       "student_name":"Student 4", 
       "student_id":4, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 4" 
      }, 
      { 
       "student_name":"Student 5", 
       "student_id":5, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 5" 
      } 
     ] 
     }, 
     { 
     "group_name":"Group 2", 
     "group_id":2, 
     "group_status":"NO_MESSAGES", 
     "group_is_active":"YES", 
     "group_students":[ 
      { 
       "student_name":"Student 6", 
       "student_id":6, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 6" 
      }, 
      { 
       "student_name":"Student 7", 
       "student_id":7, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 7" 
      }, 
      { 
       "student_name":"Student 8", 
       "student_id":8, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 8" 
      }, 
      { 
       "student_name":"Student 9", 
       "student_id":9, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 9" 
      }, 
      { 
       "student_name":"Student 10", 
       "student_id":10, 
       "student_photo":"http:\/\/placehold.it\/120x120&text=Student 10" 
      } 
     ] 
     }, 
... 

И мой код по методу на ViewController заключается в следующем:

- (void)fetchGroupsFromContext { 
    //Fetch and order alphabetical array 
    //SERVER 
    NSManagedObjectContext *contextServer = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext; 
    NSFetchRequest *fetchRequestServer = [NSFetchRequest fetchRequestWithEntityName:@"Server"]; 
    NSSortDescriptor *descriptorServer = [[NSSortDescriptor alloc]initWithKey:@"status" 
                    ascending:YES 
                    selector:@selector(localizedStandardCompare:)]; 
    fetchRequestServer.sortDescriptors = @[descriptorServer]; 
    NSError *errorServer = nil; 
    NSArray *fetchedObjectsServer = [contextServer executeFetchRequest:fetchRequestServer 
                   error:&errorServer]; 

    Server *serverList = [fetchedObjectsServer firstObject]; 
    self.server = [serverList.groups allObjects]; 

    //GROUPS 
    NSManagedObjectContext *contextGroups = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext; 
    NSFetchRequest *fetchRequestGroups = [NSFetchRequest fetchRequestWithEntityName:@"Groups"]; 
    NSSortDescriptor *descriptorGroups = [[NSSortDescriptor alloc]initWithKey:@"group_name" 
                    ascending:YES 
                    selector:@selector(localizedStandardCompare:)]; 
    fetchRequestGroups.sortDescriptors = @[descriptorGroups]; 
    NSError *errorGroups = nil; 
    self.fetchedObjectsGroups = [contextGroups executeFetchRequest:fetchRequestGroups 
                   error:&errorGroups]; 

    Groups *groupList = [self.fetchedObjectsGroups firstObject]; 
    self.groups = [groupList.students allObjects]; 
    NSLog(@"%@", self.groups); 

    [self.tableView reloadData]; 
} 

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

UPDATE: Вот что на numberOfSectionsInTableView и numberOfRowsInSection:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [self.server count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [self.groups count]; 
} 

При печати self.groups это показать мне это:

(
    "<Students: 0x7f98e8cc5bc0> (entity: Students; id: 0xd000000006480004 <x-coredata://191D8908-AAA2-4527-9D05-DB582D87570D/Students/p402> ; data: <fault>)", 
    "<Students: 0x7f98e8cf22f0> (entity: Students; id: 0xd000000003a80004 <x-coredata://191D8908-AAA2-4527-9D05-DB582D87570D/Students/p234> ; data: <fault>)", 
    "<Students: 0x7f98e8cb10a0> (entity: Students; id: 0xd000000002500004 <x-coredata://191D8908-AAA2-4527-9D05-DB582D87570D/Students/p148> ; data: <fault>)", 
    "<Students: 0x7f98e8cf1150> (entity: Students; id: 0xd000000006880004 <x-coredata://191D8908-AAA2-4527-9D05-DB582D87570D/Students/p418> ; data: <fault>)", 
    "<Students: 0x7f98e8cb7410> (entity: Students; id: 0xd000000002d00004 <x-coredata://191D8908-AAA2-4527-9D05-DB582D87570D/Students/p180> ; data: <fault>)" 
) 

UPDATE: The viewForHeaderInSectioncellForRowAtIndexPath

#pragma mark - UITableViewDelegate 

- (UITableViewCell *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    //Fetch all students objects 
    Groups *groupList = [self.fetchedObjectsGroups objectAtIndex:section]; 
    self.groups = [groupList.students allObjects]; 
// NSLog(@"%@", self.groups); 

    //Order array alphabetical 
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"group_name" 
                 ascending:YES 
                 selector:@selector(localizedStandardCompare:)]; 
    self.server = [self.server sortedArrayUsingDescriptors:@[sort]]; 

    HeaderTableViewCell* headerCell = [tableView dequeueReusableCellWithIdentifier:@"HeaderCell"]; 
    Groups *groupsList = self.server[section]; 
    headerCell.titleHeader.text = groupsList.group_name; 

    return headerCell; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //Order array alphabetical 
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"student_name" 
                 ascending:YES 
                 selector:@selector(localizedStandardCompare:)]; 
    self.groups = [self.groups sortedArrayUsingDescriptors:@[sort]]; 

    CellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    Students *studentsList = self.groups[indexPath.row]; 
    cell.titleCell.text = studentsList.student_name; 

    return cell; 
} 
+0

Что такое 'self.groups', когда вы распечатываете его? – Mike

+0

Также вы могли бы показать, что у вас есть для 'numberOfRowsInSection' и' numberOfSectionsInTableView'? – Mike

+0

Обновлено с 'numberOfRowsInSection' и' numberOfSectionsInTableView' и 'NSLog' @Mike –

ответ

0

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

self.groups будет массивом Group объектов, и каждый объект группы имеет nameNSString свойства и membersNSArray недвижимости. Все, что вам нужно сделать, это выборка и сортировка групп, а затем код представления таблицы может выглядеть примерно так:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return self.groups.count; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    Group *group = self.groups[section]; 
    return group.members.count; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    Group *group = self.groups[section]; 
    return group.name; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    // create your cell 
    GroupCell *cell = ..... 

    // Set this group on the cell, allowing it to update labels, etc. 
    Group *group = self.groups[indexPath.row]; 
    cell.group = group; 

    return cell; 
} 
+0

Это сработало, когда я положил' Group' в 'viewForHeaderInSection', потому что я использую пользовательский заголовок раздела. Но теперь первые 3 раздела показывают первый объект, а остальные и показывают нормальный. –

+0

Можете ли вы показать cellForRowAtIndexPath – Mike

+0

там –

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