2011-01-27 32 views
1

我已經創建了一個表格視圖並顯示了數據。當我點擊表格視圖中的數據時,我把附件標記(使用UITableViewCellAccessoryCheckmark,Like,Check Mark)。現在我想保留索引位置的狀態。因爲當我去另一個班級然後回到桌子視圖時,會顯示以前的狀態(附件標記)。那麼我怎樣才能保存狀態,這意味着存儲或保存indexpath值(不使用AppDelegate方法),那麼我該如何實現呢?如何在iPhone的表格視圖中保留索引路徑值?

這裏我的示例代碼,

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

請幫我一把。一旦你達到的範圍內結束(我不知道他們是零或釋放,我只知道你不能使用它們)

感謝

回答

1

變量是不可用的。 B)創建一個持久變量。將該值保存到持久性存儲中 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

在.M:

@implementation 
@synthesize checkedData; 
@end

現在,設置該變量:

self.checkedData = indexPath;

要檢查它:

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

真的不會有太大的不同,它取決於你決定你想要什麼。如果您使用NSUserDefaults,請記住數據在啓動時保持不變。如果你不希望這樣,但你要使用它,你需要清空對象當您關閉應用程序:[prefs removeObjectForKey:@"checkedData"];

快樂編碼,

贊恩

+0

感謝您的答覆。我正在使用NSUserDefaults,但我無法存儲索引路徑值。並且它不起作用「NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults]; if([prefs objectForKey:@」checkedData「] == indexPath){ cell.AccessoryType = UITableViewCellAccessoryCheckMark; }」。 – Pugal 2011-01-27 12:08:54

相關問題