1

我创建了一个表格视图并显示了数据。当我单击表格视图中的数据时,我放置了附件标记(使用 UITableViewCellAccessoryCheckmark、Like、Check Mark)。现在我想保留索引位置的状态。因为当我去另一个班级然后回到表格视图时,会显示以前的状态(附件标记)。那么我怎样才能保留状态,这意味着存储或保存 indexpath 值。(不使用 AppDelegate 方法)那么我该如何实现呢?

这是我的示例代码,

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

 if (newRow != oldRow)
{
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:
                                indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:
                                checkedData];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    checkedData = indexPath;

}
if (newRow == oldRow) {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } else {

        // cell.accessoryType = UITableViewCellAccessoryNone;
    }
    checkedData = indexPath;
}
 }

当返回表视图类时,应该保留之前的状态。那么我该如何访问呢?

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

    if(checkedData == indexPath) // Doesn't works
      {

    cell.accessoryType = UITableViewCellAccessoryCheckmark;
     }

请帮帮我。

谢谢

4

1 回答 1

1

一旦到达作用域的末尾,变量就不可用(我不知道它们是 nil 还是已释放,我只知道你不能使用它们)。

您想要做的是 A)将该值保存到持久存储B)创建一个持久变量。

A)将对象设置为存储(在本例中为 NSUserDefaults,因为它非常简单:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
prefs = [setObject:checkedData forKey:@"checkedData"];

然后,要以您想要的方式检查对象,您可以这样做:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:@"checkedData"] compare: indexPath]== NSOrderedSame){
cell.AccessoryType = UITableViewCellAccessoryCheckMark;
}

B)将对象保存为持久变量:

在您的 .h 中:

@interface ... : ...{

}

@property(nonatomic, retain) NSIndexPath *checkedData;

@end

在他们中:

@implementation 
@synthesize checkedData;
@end

现在,设置这个变量:

self.checkedData = indexPath;

要检查它:

if([self.checkedData compare:indexPath] == NSOrderedSame){
cell.accessoryType = UITableViewCellAccessoryTypeCheckMark;
}

真的不会有太大的不同,由你决定你想要什么。但是,如果您使用 NSUserDefaults,请记住数据会在启动时保持不变。如果您不想这样做,但又想使用它,则必须在关闭应用程序时清空对象:[prefs removeObjectForKey:@"checkedData"];

快乐编码,

赞恩

于 2011-01-27T11:49:39.333 回答