如何从NSArray填充UITableView?

时间:2014-08-29 12:28:23

标签: ios objective-c arrays uitableview

对于这个问题,我看过几个例子,但在我的情况下,有一个主要区别。我有一个类LTModel,它是另一个名为LTChallenge的类的容器:

以下是LTModel

#import <Foundation/Foundation.h>
#import "LTChallenge.h"

@interface LTModel : NSObject

@property   NSMutableArray  *challenges;
-(int) numberOfChallenges;
-(void) addChallenge:(NSString *) challengeName;
-(LTChallenge*) challengeAtIndex:(NSInteger) index;
@end

以下是LTChallenge

@interface LTChallenge : NSObject

@property   NSString *name;
@property   NSMutableArray *times;
- (instancetype)init:(NSString *)challengeName;
- (void) addObject:(LTTime *) time;
@end

现在我的UITableViewController我试图以挑战的名义填满我的桌子。首先,我给他们价值:

- (void)viewDidLoad
{
    [super viewDidLoad];   
    //Instantiate
    lapTimerModel = [[LTModel alloc] init];
    [lapTimerModel addChallenge:@"Clap 20 times"];
    [lapTimerModel addChallenge:@"Say the alphabet"];
    [lapTimerModel addChallenge:@"100 Meter Sprint Challenge"];
    [lapTimerModel addChallenge:@"Read the IOS al spec challenge"];
}

最后,我在这里填写了我需要挑战名称的表格:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [lapTimerModel numberOfChallenges];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [lapTimerModel challengeAtIndex]; //???? Maybe in this line I need challenges array in LTModel, I used this but did not work

// cell.textLabel.text = [lapTimerModel.challenges objectAtIndex:indexPath.row];
    return cell;
}

如何在我标有问号的行中使用objectAtIndex:indexPath.row?感谢任何建议。

修改

以下是challengeAtIndex

的实施
-(LTChallenge*) challengeAtIndex : (NSInteger) index{

    return [_challenges objectAtIndex:index];
}

1 个答案:

答案 0 :(得分:1)

挑战不是NSString。并且您需要将NSString分配给cell.textLabel.text:

LTChallenge *challenge = [lapTimerModel challengeAtIndex:indexpath.row];
cell.textLabel.text = challenge.name;