NSIndexPath对象显示为NSArray对象



我正在开发一个应用程序,其中我已将iVar声明为NSIndexPath对象,但它显示为didSelectRowAtIndexPath中的NSArray对象。事情怎么会变成这样,我到底犯了什么错误?请帮帮我。提前谢谢。

示例代码:

//.h file:
NSIndexPath *lastIndexPath;
//.m file:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      if([[default1 objectForKey:@"keyToRepeatString"] isEqualToString:[arrayRepeat   objectAtIndex:i]])
        {
            lastIndexPath=indexPath;
            repeatString=[default1 objectForKey:@"keyToRepeatString"];
        }
}
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
int newRow = [indexPath row];
    int oldRow = [lastIndexPath row];
 }
    int oldRow = [lastIndexPath row];........//Here lastIndexPath shows as NSArray obj?

看起来像是内存管理问题:

lastIndexPath=indexPath

这一行没有告诉indexPath挂起:)

你需要用这个代替:

[lastIndexPath autorelease];
lastIndexPath = [indexPath retain];

首先,它告诉任何先前的lastIndexPath您已经完成了它。然后它告诉indexPath不要被释放,这样内存就不会被用于其他任何东西(在您的例子中,是NSArray)。

如何声明指针与指针指向的对象类型关系不大。Objective-C是非常松散的类型,你可以分配,例如,一个UIViewController地址给一个NSString指针,只要你混淆了分配,这样编译器中非常弱的类型检查就不会报错。

所以你可以将一个NSArray地址分配给一个NSIndexPath指针,在你尝试使用这个值之前什么都不会发生。

同样,正如Aliaksandr所建议的,如果你没有保留一些应该保留的东西,地址"后面"的对象可能会被释放,然后作为完全不同的东西重新分配。(这个问题特别依赖于时间/场景,并且可能导致代码在模拟器上工作,但在硬件上失败。)

我昨天遇到了一个非常类似的问题(别人写的一些旧代码中的bug神秘地开始失败)。我最终不得不通过代码在多个位置对指针的descriptionretainCount进行NSLog,以检测在什么情况下它被改变了,以及为什么。(问题是在另一个类中不正确地声明了属性assign)

最新更新