Swift, save string in property list

551 Views Asked by At

I've a plist file named as "data.plist" like this: enter image description here

I have six arrays, and I also have 6 buttons and a text field. I would like to save the string in the text field to the correct array when I press the right button.

3

There are 3 best solutions below

2
vadian On BEST ANSWER

There are many approaches, here is one:

  • Name the keys for the arrays in the plist dictionary livello_0 - livello_5.
  • Assign tags 0 - 5 to the buttons (indexes are zero-based).
  • When a button is pressed, get the tag (let tag = sender.tag) and get the array with let array = data["livello_\(tag)"].
  • Update / write the value.
  • If it is a Swift collection type, assign the array back to the dictionary (value semantics).
0
dRAGONAIR On

Make the changes as below.

Structure of the pList: Make the button titles as the keys in the plist.

Logic to save: When a button is pressed, fetch the array of the button's title and save the text from the textField into the array. Update this new array as the value for the key(selectedButton's title)

0
Saurav On
  1. Set tag to each buttons in a pattern. eg. Button tag corresponding to 0th row of plist will be 0+1000
  2. By doing this you will get the corresponding index of array in plist when user taps the button by doing (tag-1000)
  3. On button tap get the string from text field and save to plist.

Note: It is necessary to set tag more than 0 because by default all the ui elements have 0 as tag.