Проблема с массивами в разделах (TableView) - PullRequest
0 голосов
/ 27 ноября 2011

У меня проблема с тем, что мои массивы не настроены на те секции, которые я хочу. В коде под:

  • (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) раздел

В секцию задан только второй массив, но он повторяет себя в двух других секциях и не устанавливает остальные секции вместе с остальными массивами.

Еще одна вещь, которую я имею - если я добавлю в один из массивов (скажем, третий) более 5 строк, таких как первый и второй массив, это выдаст мне ошибку: Завершение приложения из-за необработанного исключения «NSRangeException», причина: '* - [__ NSArrayM objectAtIndex:]: индекс 5 за пределами [0 .. 4]'

Что я делаю не так ?? Спасибо за помощь!

код:

(SectionArray и dataArray являются переменными NSMutableArray в моем файле .h)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
sectionArray =  [NSArray arrayWithObjects:@"section1", @"section2", @"section3", nil];

return [sectionArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:        (NSInteger)section
{

NSString *sectionHeader = nil;

    if(section == 0)
    {
        sectionHeader = @"אתרים חשובים";
    }

    if(section == 1)
    {
        sectionHeader = @"מתעניינים";
    }

    if(section == 2)
    {
        sectionHeader = @"טלפונים שימושיים";
    }

return sectionHeader;
}

// Returns the number of rows in a given section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{        
    if(section == 0)
    {
        dataArray = [[NSMutableArray alloc] initWithObjects:
                     @"אתר אורנים",
                     @"כניסה למערכת ניהול שיעורים",
                     @"אלפון אנשי סגל",
                     @"אתר אגודת הסטודנטים",
                     @"מפת אורנים", nil];
    }

    if(section == 1)
    {
        dataArray = [[NSMutableArray alloc] initWithObjects:
                     @"תנאי קבלה",
                     @"שאלות נפוצות",
                     @"הרשמה אונליין",
                     @"יצירת קשר עם יועץ לימודים",
                     @"תחבורה ציבורית", nil];
    }

    if(section == 2)
    {
        dataArray = [[NSMutableArray alloc] initWithObjects:
                     @"מרכז המידע וההרשמה",
                     @"שכר לימוד",
                     @"שכר לימוד (מספר נוסף)",
                     @"קופת אורנים",
                     @"מרכז ההשאלה בספריה", nil];
                    /* 
                    @"תמיכת הספריה",
                     @"מעונות",
                     @"מכלול",
                     @"רכז בטחון",
                     @"שער",
                     @"אגודת הסטודנטים",
                     @"רדיו אורנים",
                     @"פקולטות:",
                     @"מנהל תלמידים",
                     @"מנהל תלמידים (מספר נוסף)", nil];
                      */
    }

    return [dataArray count];
}

// Returns the cell for a given indexPath.
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    // Create the cell.
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:CellIdentifier];
}

cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.textAlignment = UITextAlignmentRight;

float Rvalue = (1.0 * 000) / 255;
float Gvalue = (1.0 * 139) / 255;
float Bvalue = (1.0 * 69) / 255;
cell.textLabel.textColor = [UIColor colorWithRed:Rvalue green:Gvalue blue:Bvalue   alpha:1.0f];

UIImage *cellImage = [UIImage imageNamed:@"oranimCellIco.png"];
cell.imageView.image = cellImage;

return cell;
}

Ответы [ 2 ]

2 голосов
/ 27 ноября 2011

Прежде всего, вы должны создавать и хранить ваши данные вне методов делегата. В -(void)viewDidLoad; или -(id)init; на самом деле это не имеет значения. Что важно, так это то, что ваш массив данных (или массивы, или массивы массивов) должен быть создан до вызова делегата и должен оставаться постоянным, пока табличное представление вызывает его делегата для данных.

Допустим, некоторый viewController.h

@property(nonatomic, retain)NSArray data;
@property(nonatomic, retain)NSArray sections;

и соответствующий viewController.m

-(void)viewDidLoad{
    [super viewDidLoad];
    self.sections = [[NSArray alloc] initWithObjects:@"אתרים חשובים",@"מתעניינים",@"טלפונים שימושיים",nil];
    self.data = [[NSArray alloc]initWithObjects:
                 [[NSArray alloc] initWithObjects:
                 @"אתר אורנים",
                 @"כניסה למערכת ניהול שיעורים",
                 @"אלפון אנשי סגל",
                 @"אתר אגודת הסטודנטים",
                 @"מפת אורנים", nil],
                 [[NSArray alloc] initWithObjects:
                 @"תנאי קבלה",
                 @"שאלות נפוצות",
                 @"הרשמה אונליין",
                 @"יצירת קשר עם יועץ לימודים",
                 @"תחבורה ציבורית", nil],
                 [[NSArray alloc] initWithObjects:
                 @"מרכז המידע וההרשמה",
                 @"שכר לימוד",
                 @"שכר לימוד (מספר נוסף)",
                 @"קופת אורנים",
                 @"מרכז ההשאלה בספריה", nil]nil];
}

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [self.sections objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray* dataArray = [self.data objectAtIndex:indexPath.section];
    return [dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){
        // Create the cell.
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:CellIdentifier];
    }

    NSArray* dataArray = [data objectAtIndex:indexPath.section];
    cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
    cell.textLabel.textAlignment = UITextAlignmentRight;

    cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:139.0/255.0 blue:69.0/255.0 alpha:1.0];

    UIImage *cellImage = [UIImage imageNamed:@"oranimCellIco.png"];
    cell.imageView.image = cellImage;

    return cell;
}

קצת סדר בקוד לא יפגע אף פעם:)

0 голосов
/ 27 ноября 2011

Проблема в том, что не определено, как TableView будет вызывать методы делегирования.В вашем коде это будет работать только в том случае, если tableView:cellForRowAtIndexPath: будет вызываться для каждого раздела только после tableView:numberOfRowsInSection для этого раздела.

Ваши проблемы будут решены, если вы сохраните все, что имеете доступ к даннымдля всех разделов одновременно.Например, вы можете использовать 3 различных массива для (по одному для каждого раздела) или использовать массив массивов для хранения элементов.

...