使用indexPath.row从数组中获取对象

时间:2012-05-05 00:11:03

标签: objective-c xcode uitableview

如何使用indexPath.row从数组中获取对象?我尝试使用以下代码,但它返回“signal SIGABRT”..请帮助

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    NSString *inde = [NSString stringWithFormat:@"%d", indexPath.row];
    NSNumber *num = [NSNumber numberWithInteger: [inde integerValue]];
    int intrNum = [num intValue];
    NSString *name = [basket objectAtIndex:intrNum];


    cell.textLabel.text = name;
    return cell;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    basket = [[NSMutableArray alloc] init];
    [basket addObject:@"1"];
    [self makeGrid];
 }


- (void)addToBasket:(id)sender {
    NSInteger prodID = ((UIControl*)sender).tag;

    [basket insertObject:[NSNumber numberWithInt:prodID] atIndex:0];
    [self.tableView reloadData];
}

错误讯息:

-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x6866080 2012-05-05 02:29:18.208 app[7634:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x6866080'

3 个答案:

答案 0 :(得分:3)

为什么不使用

NSString *name = [basket objectAtIndex:indexPath.row];

答案 1 :(得分:1)

addToBasket方法中,您将NSNumber对象放入basket数组,但在cellForRowAtIndexPath方法中,您希望NSString中有basket个对象。要使代码正常工作,您可以使用安全转换为字符串:

NSString *name = [NSString stringWithFormat:@"%@",[basket objectAtIndex:intrNum]];

答案 2 :(得分:0)

当你的代码

int intrNum = [num intValue];

intrNum可能不是真正的IndexPath Integer它可能返回地址类型(例如' 88792'等等)。因此,它会导致数组出现问题

cellForRowAtIndexPath中的数组代码中纠正您的get对象

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

/* NSString *inde = [NSString stringWithFormat:@"%d", indexPath.row];
NSNumber *num = [NSNumber numberWithInteger: [inde integerValue]];
int intrNum = [num intValue]; */

NSString *name = [basket objectAtIndex:indexPath.row];


cell.textLabel.text = name;
return cell;

}

并在addToBasket中,您不应该使用numberWithInt,就像我上面提到的int的原因一样。

- (void)addToBasket:(id)sender {
    NSInteger prodID = ((UIControl*)sender).tag;

    // [basket insertObject:[NSNumber numberWithInt:prodID] atIndex:0];
    [basket insertObject:[NSNumber numberWithInteger:prodID] atIndex:0];    

    [self.tableView reloadData];
}

希望它可以帮到你!