2014-09-21 36 views
0

我需要通過類的對象數組 我已經類稱爲學生,它有一些屬性(名稱,代碼,ACCOUNT_TYPE ....);目標C - 傳遞對象的數組表視圖

我調用數據庫的方法來獲取所有招生對象

Student_array = [data_base_helper selectAllStudents]; 

我需要顯示在表視圖學生名單,我製作的其它陣列叫名字

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString * cell_identifer = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_identifer forIndexPath:indexPath]; 

    // Configure the cell... 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_identifer]; 
    } 



for(Student * st in student_array){ 
     [self.names addObject:st.student_name]; 
    } 

    cell.textLabel.text = [names objectAtIndex:indexPath.row ]; 

    return cell; 
} 

我發現一些問題與刪除,因爲我通過指數的想法刪除如何傳遞對象數組中的表視圖

回答

2

的想法是,你並不需要使用「名稱的數組」,你可以用你的學生直接rray,以這樣的方式

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString * cell_identifer = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_identifer forIndexPath:indexPath]; 
    // Configure the cell... 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_identifer]; 
    } 

    Student *student = Student_array[indexPath.row]; 
    cell.textLabel.text = student.student_name; 

    return cell; 
} 

當你需要刪除從一個的tableView學生,你可以很容易地從數組中刪除,然後相應地更新的tableView,類似的東西:

[Student_array removeObjectAtIndex:indexPath.row]; 
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

注意,在上面的代碼我假設你想在給定indexPath.row和Student_array刪除的對象是NSMutableArray而不是NSArray

PS:您可能需要重命名Student_array in students因爲在objective-c中,用大寫字母命名對象並不是一個好習慣,也不是使用下劃線。可能我也會重命名student_namename,因爲學生只是對象類型的重複。

0

當您刪除從表中的單元格中刪除相應的刪除單元兩個陣列Student_array和self.name數組項。