How to preserve the index path value in the table view in iPhone?

陌路散爱 提交于 2019-12-08 03:21:27

Variables are unavailable once you reach the end of scope (I don't know if they're nil or released, I just know you can't use them).

What you want to do is A) save that value to persistent storage or B) make a persistent variable.

A) Set the object to storage (In this case NSUserDefaults, because it's dead easy:

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

Then, to check the object the way you wanted to, you could do this:

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

B) Save the object as a persistent variable:

In your .h:

@interface ... : ...{

}

@property(nonatomic, retain) NSIndexPath *checkedData;

@end

In the .m:

@implementation 
@synthesize checkedData;
@end

Now, to set this variable:

self.checkedData = indexPath;

To check it:

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

There really isn't going to be a whole lot of difference, it's up to you to decide what you want. If you use NSUserDefaults though, keep in mind that the data persists across launches. If you don't want that, but you want to use it you have to empty the object when you close the app: [prefs removeObjectForKey:@"checkedData"];

Happy coding,

Zane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!