0

如何使用 indexPath.row 从数组中获取对象?我已尝试使用以下代码,但它返回“信号 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'
4

3 回答 3

3

你为什么不直接使用

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

?

于 2012-05-05T00:25:41.553 回答
1

addToBasket方法中,您将NSNumber对象放入数组basket中,但在cellForRowAtIndexPath方法中,您期望. 为了使您的代码正常工作,您可以使用安全转换为字符串:NSStringbasket

NSString *name = [NSString stringWithFormat:@"%@",[basket objectAtIndex:intrNum]];
于 2012-05-06T07:39:07.587 回答
0

当你的代码

int intrNum = [num intValue];

可能不是真正的intrNumIndexPath 整数,它可能会返回地址类型(例如“88792”等)。所以,它会导致你的阵列出现问题

cellForRowAtIndexPath像这样从数组代码中更正您的获取对象

- (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];
}

希望对你有帮助!

于 2012-05-06T08:37:05.603 回答