Search code examples
objective-cuitableviewnsuserdefaultsnsindexpath

Can't save indexPath.row to NSUserDefaults


I'm trying to save my tableview's rows that can be moved (indexPath.row) to NSUserdefaults but i'm out of success, it doesn't work or the app craches.. Whats's missing/wrong?

 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
    {
        NSString *stringToMove = self.objects[sourceIndexPath.row];
        [self.objects removeObjectAtIndex:sourceIndexPath.row];
        [self.objects insertObject:stringToMove atIndex:destinationIndexPath.row];


    }

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //save indexPath 
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        int index = indexPath.row;
        [userDefaults setInteger:index forKey:@"saverows"];
        [userDefaults synchronize];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //load indexPath
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSInteger loadrows = [userDefaults integerForKey:@"saverows"];
        NSIndexPath *newIndex = [NSIndexPath indexPathWithIndex:loadrows];
        self.objects[indexPath.row]=newIndex;

        //rows
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text=self.objects[indexPath.row];
        return cell;
    }

Solution

  • The problem is that you are trying to add NSIndexPath as a text for the UILabel

    You can't do this

    NSIndexPath *newIndex = [NSIndexPath indexPathWithIndex:loadrows];
    self.objects[indexPath.row]=newIndex;
    

    Then doing this

    cell.textLabel.text=self.objects[indexPath.row];
    

    In the first part you are adding an NSIndexPath and then treating it as NSString and add it to the UILabel.


    Update 1

    To Save the order of the cells you can save the entire array (since it is array of strings)

    In moveRowAtIndexPath: method add this at the end

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.objects forKey:@"saverows"];
    [userDefaults synchronize];
    
    • Remove what you are doing under save indexPath in didSelectRowAtIndexPath method
    • Remove What you are doing under load indexPath in cellForRowAtIndexPath method

    In viewDidLoad method add the following

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.objects = [userDefaults objectForKey:@"saverows"];