4

I've two UITableView with custom cell, the first UITableView has array of string in UILabel and UIButton.

This is my FirstViewController(first UITableView)

enter image description here

And the secondViewController( second UITableView) has only UILabel.

What I'm trying to do is to click for example at the second cell UIButton "add to second table" and pass it in an array using NSUserDefaults into the secondViewController, and when i click at the first cell UIButton "add to second table" it should keep the first value and append this value with it and add it to the secondViewController.

This is my code (in firstViewController) but as you can see here I'm sending the whole array every time, is it possible to send each time String and append it together in an array in NSUserDefaults and then retrieve it in the second UITableView:

func add(sender:AnyObject){
        NSUserDefaults.standardUserDefaults().setObject(array, forKey: "Array")
    }

i tried to send it this way but its only sending one String not an Array of Strings :

func add(sender:AnyObject){
        NSUserDefaults.standardUserDefaults().setObject(array[sender.tag], forKey: "Array")
    }

Code in the secondViewController :

if (NSUserDefaults.standardUserDefaults().stringForKey("Array") != nil){
    array  =  NSUserDefaults.standardUserDefaults().objectForKey("Array")! as! NSArray
}

1 Answer 1

2

Update your code with following code:

func add(sender:AnyObject){
if (NSUserDefaults.standardUserDefaults().stringForKey("Array") != nil){
    array1  =  NSUserDefaults.standardUserDefaults().objectForKey("Array")! as! NSArray
}
 array1.append(array[sender.tag])
 NSUserDefaults.standardUserDefaults().setObject(array1, forKey: "Array")
 NSUserDefaults.standardUserDefaults().synchronize()
}

Code in the secondViewController :

  if (NSUserDefaults.standardUserDefaults().stringForKey("Array") != nil){
        array  =  NSUserDefaults.standardUserDefaults().objectForKey("Array")! as! NSArray
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is passing the whole array, I'm saying i need to pass Strings and append them in array. like array[indexPath.row]
its only appending one value, when i click on add to fav for second and third value, i have only one value in the second table !! also its forcing me to cast it to String like : array.append(NSUserDefaults.standardUserDefaults().objectForKey("Array")! as! NSString as String)
array1 is of type what ?
is it possible to check if the item that is being added exist already in NSUserdefaults array before adding it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.