NSUserDefault not loading in table view - ios

I have a main view with a button that when pressed it adds the url from the web view(like a bookmark) to a table view. The only problem is that its not loading. ive been at it for hours now but cant figure it out. I think i am loading the data in the table view wrong but not quiet sure.
This is the MainViewController.m
- (IBAction)bookmark:(id)sender {
UIActionSheet *actionSheet =
[[UIActionSheet alloc] initWithTitle:[[[[self webView] request] URL]
absoluteString] delegate:nil cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil otherButtonTitles:#"Add", nil];
[actionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSMutableArray *bookmarks = [[[NSUserDefaults standardUserDefaults]
arrayForKey:#"Bookmarks"] mutableCopy];
if (!bookmarks) {
bookmarks = [[NSMutableArray alloc] init];
}
[bookmarks addObject:[[[[self webView]request] URL] absoluteString]];
[[NSUserDefaults standardUserDefaults] setObject:bookmarks
forKey:#"Bookmarks"];
}
}
This is BookmarksViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", bookmarks);
bookmarks = [[[NSUserDefaults standardUserDefaults]
arrayForKey:#"Bookmarks"] mutableCopy];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:#"Bookmarks"];
cell.textLabel.text = [self.bookmarks objectAtIndex:indexPath.row];
return cell;
}

When your app is first run there is nothing set for the Bookmarks key in NSUserDefaults. So the line:
bookmarks = [[[NSUserDefaults standardUserDefaults]
arrayForKey:#"Bookmarks"] mutableCopy];
in viewDidLoad leaves bookmarks set to nil.
In your action sheet handler you actually deal with this properly.
And one other big problem is the call to:
[[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:#"Bookmarks"];
in your cellForRowAtIndexPath... method. Why do you update NSUserDefaults every time a cell is needed? Don't do this.

The command [tableView dequeueReusableCellWithIdentifier:CellIdentifier] does NOT always return a cell. It only returns a cell if there is a cell in the reusable-cell queue.
So your method should be:
- (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];
}
[[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:#"Bookmarks"];
cell.textLabel.text = [self.bookmarks objectAtIndex:indexPath.row];
return cell;
}

Related

UiTableview values not getting update upon the array value changed

I am fetching data from a web service which returns an array and I am displaying that array in the table view. I am facing the issue that table values are getting updated but after some time as first it is showing the old value and upon scrolling it shows the new value.
Below is my code.
NSURLRequest *request=[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:8.0];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableDictionary *ResultdicNew = [[NSMutableDictionary alloc]initWithDictionary:(NSMutableDictionary *)responseObject];
NSString *message=[ResultdicNew objectForKey:#"status"];
NSString *message1=#"";
if([message isEqualToString:#"success"])
{
NSMutableDictionary *datadic=[ResultdicNew objectForKey:#"data"];
NSMutableDictionary *listDataDic=[datadic objectForKey:#"competitors"];
affArray=[listDataDic valueForKey:#"affiliation"];
countArray=[listDataDic valueForKey:#"total_count"];
_lblEventTitle.text=[datadic valueForKey:#"group_name"];
NSLog(#"affArray here is %#",affArray);
NSLog(#"countArray.count here is %ld",countArray.count);
[self revealCompetitorsView];
}
else
{
message1=[Resultdic objectForKey:#"data"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message1
message:message
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
[SVProgressHUD dismiss];
// NSLog(#"JSON Here is :%lu",(unsigned long)Resultdic.count);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
#pragma mark - UITableView Datasource, Delegate Methods
#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [countArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
static NSString *CellIdentifier = #"menuCellNew";
cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"RAMenuCellNew" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// [cell SetData:[m_ary objectAtIndex:indexPath.row]];
UILabel *lbl=(UILabel*)[cell viewWithTag:420];
UILabel *lbl1=(UILabel*)[cell viewWithTag:421];
lbl.text=[affArray objectAtIndex:indexPath.row];
lbl1.text=[countArray objectAtIndex:indexPath.row];
}
[self.sideTable reloadData];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%ld",(long)indexPath.row);
}
Your problem is in your cellForRowAtIndexPath - you are not updating the cell when you are given an existing cell for reuse.
You need to move the updating of the cell fields outside of the if (cell==nil)... block -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
static NSString *CellIdentifier = #"menuCellNew";
cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"RAMenuCellNew" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// [cell SetData:[m_ary objectAtIndex:indexPath.row]];
UILabel *lbl=(UILabel*)[cell viewWithTag:420];
UILabel *lbl1=(UILabel*)[cell viewWithTag:421];
lbl.text=[affArray objectAtIndex:indexPath.row];
lbl1.text=[countArray objectAtIndex:indexPath.row];
return cell;
}
Also, you can register your nib file for your cell in viewDidLoad and then you can use dequeueReusableCellWithIdentifer:forIndexPath which will automatically allocate a new cell if required and you can skip the whole if (cell==nil... bit.
You should also consider creating a UITableViewCell subclass and then you can assign your text fields to IBOutlet properties instead of searching by tag.
Replace this code on cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
static NSString *CellIdentifier = #"menuCellNew";
cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"RAMenuCellNew" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// [cell SetData:[m_ary objectAtIndex:indexPath.row]];
UILabel *lbl=(UILabel*)[cell viewWithTag:420];
UILabel *lbl1=(UILabel*)[cell viewWithTag:421];
lbl.text=[affArray objectAtIndex:indexPath.row];
lbl1.text=[countArray objectAtIndex:indexPath.row];
return cell;
}

Store Displayed UITableView Cell in NSString if Displayed for 2 Seconds

I have a UITableView with many cells in it. I want to track which cells are scrolled over and store an associated ID in NSUserDefaults.
This all works extremely well, but now I would like to add a timer that prevents the ID from being appended to the string unless it has been displayed on the screen for a full two seconds or more.
Here is the line where I append each new scrolled ID to the NSString:
NSString *scrolledIdPre = [NSString stringWithFormat:#"-%#-", locationId];
Here is my full method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
NSDictionary *item;
if (tableView == self.searchDisplayController.searchResultsTableView){
item = [[NSDictionary alloc] initWithDictionary:[filteredListItems
objectAtIndex:indexPath.row]];
}else {
item = [[NSDictionary alloc] initWithDictionary:[listItems
objectAtIndex:indexPath.row]];
}
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"cell"];
}
NSString *locationId = [item objectForKey:#"location_id"];
NSString *scrolledIdPre = [NSString stringWithFormat:#"-%#-", locationId];
[scrolledIds appendString:scrolledIdPre];
[[NSUserDefaults standardUserDefaults] setObject:scrolledIds forKey:#"impressions"];
[[NSUserDefaults standardUserDefaults] synchronize];
return cell;
}
Any ideas would be wonderful. Thank you!
You can use dispatch with delay and the check if cell is still visible
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
NSDictionary *item;
if (tableView == self.searchDisplayController.searchResultsTableView){
item = [[NSDictionary alloc] initWithDictionary:[filteredListItems
objectAtIndex:indexPath.row]];
}else {
item = [[NSDictionary alloc] initWithDictionary:[listItems
objectAtIndex:indexPath.row]];
}
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"cell"];
}
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// nil means that cell is no longer visible so it didn't meet the requirement for 2s displaying
if ([tableView cellForRowAtIndexPath:indexPath] == nil) {
return;
}
NSString *locationId = [item objectForKey:#"location_id"];
NSString *scrolledIdPre = [NSString stringWithFormat:#"-%#-", locationId];
[scrolledIds appendString:scrolledIdPre];
[[NSUserDefaults standardUserDefaults] setObject:scrolledIds forKey:#"impressions"];
[[NSUserDefaults standardUserDefaults] synchronize];
});
return cell;
}

App crashes when button is pressed that points to table view

I've got a button pointing to a view and whenever I see press the button my app crashes. Can anyone tell me why? The code is the implementation file for the view that the button pushes to.
#implementation OpenShiftViewController
-(void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
myDictionary = [defaults dictionaryRepresentation];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myDictionary.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray * allKeys = [myDictionary allKeys];
cell.textLabel.text = [myDictionary objectForKey:[allKeys objectAtIndex:indexPath.row]];
cell.detailTextLabel.text = [myDictionary objectForKey:[allKeys objectAtIndex:indexPath.row]];
return cell;
}
#end
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
myDictionary = [defaults dictionaryRepresentation];
myMutableArray = [[NSMutableArray alloc]init];
[self storingObjectsFromDictionaryToArray];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)storingObjectsFromDictionaryToArray
{
NSArray *arr = [myDictionary allKeys];
[myMutableArray addObjectsFromArray:[myDictionary valueForKey:[arr objectAtIndex:0]]];
NSString *str = [NSString stringWithFormat:#"%#",[myDictionary valueForKey:[arr objectAtIndex:1]]];
[myMutableArray addObject:str];
str = [NSString stringWithFormat:#"%#",[myDictionary valueForKey:[arr objectAtIndex:2]]];
[myMutableArray addObject:str];
[myMutableArray addObjectsFromArray:[myDictionary valueForKey:[arr objectAtIndex:3]]];
[myMutableArray addObject:[myDictionary valueForKey:[arr objectAtIndex:4]]];
[myMutableArray addObjectsFromArray:[myDictionary valueForKey:[arr objectAtIndex:5]]];
[myMutableArray addObjectsFromArray:[myDictionary valueForKey:[arr objectAtIndex:6]]];
[myMutableArray addObject:[myDictionary valueForKey:[arr objectAtIndex:7]]];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myMutableArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [myMutableArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [myMutableArray objectAtIndex:indexPath.row];
return cell;
}
The error is Thread 1: breakpoint 9.1
Ahm ... you might have a breakpoint activated ?
You are not getting an error - it is just cause of you having an activated breakpoint.
If you're using Xcode 4, then you can see 'Breakpoints' as seen below. Just click on that to disable breakpoints.
If you are using Xcode 5, then you have to click this Blue button to disable the breakpoint.
As AlexVogel pointed out in the comments, use init method to initialize the dictionary.
Alternatively, you can use lazy loading using property:
- (NSDictionary *)myLoadedDictionary{
if (!myDictionary) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
myDictionary = [defaults dictionaryRepresentation];
}
return myDictionary;
}
Now, in your class, consume [self myLoadedDictionary] instead of myDictionary.
I am not on my machine, but I am pretty much sure that you can define even myDictionary as a getter so that you can use that same name in your code and not myLoadedDictionary.
Like everyone else I would like to point out that should post your error.
Now I also see one problem with cellAtindexPath logic. Your trying to set data on null cell, see [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; will only give you something back if you've already given it something.
You've two options for loading a cell, the new way or the old way, both are kinda of same.
Option one and I recommend this one:
in your viewDidLoad (or what not) register a class for a cell identifer:
[self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
In CellForIndexPath to get the cell go:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
The forIndexPath is important here, using old api will return a nil cell.
Option 2:
Load a cell and if its nil, create a it.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
}

Xcode show UIAlertView after UITableRowSelection?

this is my first question, sorry if something is wrong
Well I'm trying to create a view in which i can select a friend from a table view and then it should say the number and the mail on a UIAlertView but I dont know how to do this
the friend list is obtained from an xml file on my site, and then is parsed an showed on a table with a custom cell design
this is the code that creates each cell
- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:#"ContactListItem"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ContactListItem" owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
}
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
UILabel *userLabel = (UILabel *)[cell viewWithTag:2];
userLabel.text = [itemAtIndex objectForKey:#"user"];
return cell;
}
thanks
Santiago
You have to implement the didSelectRowAtIndexPath: method.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *name = [itemAtIndex objectForKey:#"user"];
NSString *email = [itemAtIndex objectForKey:#"email"];
NSString *phone = [itemAtIndex objectForKey:#"phone"];
NSString *messageStr = [NSString stringWithFormat:#"Email : %#\nPhone : %#", email, phone];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name message:messageStr delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath is the method you would need to implement. This is assuming the view you are presenting the table view in is the delegate for the table view.
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//Alert view logic happens here getting all the cell information
}

How to save tableView cell's checkmark after reload view use NSUserDefaults?

I'm new to ios development, and I'm using checkmark for cells in a UITableView.
I want storing checked cell in a NSUserDefaults database, When I reload the app, the checked cell that previously selected will be display, I'm try to defferent ways, but still failed to implement it.
Anybody can help me? I would be highly appreciate it. Sorry, my english is not good.
My code is below:
#import "FirstRowSubview.h"
#interface FirstRowSubview ()
#end
#implementation FirstRowSubview
#synthesize array = _array;
#synthesize lastIndexPath = _lastIndexPath;
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:#"ffgfgh", #"564654", #"56548", #"fgmjfgmf", #"ggkdj", nil];
self.array = list;
[list release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.array = nil;
}
#pragma mark -
#pragma mark - TableView Datasource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *subviewCells = #"Cells";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:subviewCells];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:subviewCells];
}
NSUInteger oldRow = [_lastIndexPath row];
cell.accessoryType = (indexPath.row == oldRow && _lastIndexPath != nil) ?
UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
cell.textLabel.text = [_array objectAtIndex:indexPath.row];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:_lastIndexPath.row] forKey:#"lastIndexPath"];
[defaults synchronize];
return cell;
}
#pragma mark -
#pragma mark - TableView Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int newRow = [indexPath row];
int oldRow = (_lastIndexPath != nil) ? [_lastIndexPath row] : -1;
if (newRow != oldRow) {
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
[indexPath retain];
[_lastIndexPath release];
_lastIndexPath = indexPath;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
It can be easy to store and retrieve checked cell(s) information with NSUserDefaults.
NSUserDefaults can store the data interms of Key / Value pair. Here in your case value could be boolean and key could combination of NSString & indexpath.row from UITableView.
You can make a functions like,
- (NSString *)getKeyForIndex:(int)index
{
return [NSString stringWithFormat:#"KEY%d",index];
}
- (BOOL) getCheckedForIndex:(int)index
{
if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES)
{
return YES;
}
else
{
return NO;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Here, you can check for previously checked cells like
static NSString *subviewCells = #"Cells";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:subviewCells];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:subviewCells];
}
cell.textLabel.text = [_array objectAtIndex:indexPath.row];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//Use checkedCellAtIndex for check or uncheck cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self checkedCellAtIndex:indexPath.row];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
P.S. Please, note that, this method will only useful and suggested if order of data from your NSArray will always in same order. Other then NSUserDefaults you've options like SQLite Database or plist file or any other option! Thanks :)
This is a basic example of how to create an array of NSIndexPaths based on the current selection of the table and then saving that array into NSUserDefaults.
-(void)viewDidLoad
{
[super viewDidLoad];
for (NSIndexPath *indexPath in [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:#"mySavedMutableArray"]) {
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
Here you can add objects to the array as they are selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:#"mySavedMutableArray"] addObject:indexPath];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Here you'll remove the deselected object from the array.
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:#"mySavedMutableArray"] removeObject:indexPath];
[[NSUserDefaults standardUserDefaults] synchronize];
}
The simplest way to get your code working is just put one line in view did load method as follow:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults valueForKey:#"lastIndexPath"])
_lastIndexPath = [defaults valueForKey:#"lastIndexPath"];
This will solve your problem :)
Happy Coding :)

Resources