1

How to create an array in the firebase 3.0 and perform the functions of append and delete in the array

This is the data structure i am looking for:-

1-UserIds
  --0.)   12345
  --1.)   678910
  --2.)   1112131415
2-UserProfile
  --0.)  12345
         -0.)  userName : "Rayega"
         -1.)  friends : ["Julian","Mary","Powers"]
  --1.)  678910
         -0.)  userName : "Morse"
         -1.)  friends : ["Polme","Mary","Finn"]
  --2.)  1112131415
         -0.)  userName : "Tanya"
         -1.)  friends : ["Ester","Hulio","Julian"]

i want to create an array like UserIds and like friends in every child of my user profile and be able to append and delete data from those arrays.I know how to create a dictionary but how would i go around storing an array in that dictionary and be able to perform append and delete functions in it.

I am storing UserIds array because i need to display info of every user in a tableView.

Dravidian
  • 9,945
  • 3
  • 34
  • 74

2 Answers2

3

As the links provided by Ivan explain, arrays are seldom a good idea in a database where multiple users are concurrently adding/changing the data. There also seems to be no need to store the friend list as an array. It's actually more efficient to store it as a set of user ids. That way, you're automatically guaranteed that each user id can be in the set only once.

Users: {
   12345: "Rayega",
   67890: "Morse",
   24680: "Tanya",
   13579: "Julian",
   86420: "Mary",
   97531: "Powers"
},
UserFriends: {
   12345: {
      13579: true,
      86420: true,
      97531: true
   },
   67890: {
      86420: true,
      24680: true,
      97531: true
   }
}

That last structure is called an index and is covered in the Firebase documentation under creating data that scales.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • And how will you append/addObject to this dictionary(UserFriends/12345), also how can i retrieve the userId's of my users which are actually a dictionary key to another dictionary(basically how can i get `12345`, `67890`.... and append it in a local array.. or anything..). – Dravidian Jul 17 '16 at 15:27
2

There is no native support for arrays in Firebase. But you can store the objects as a dictionary with an integer as key, and increment the key for every object you store. Then when you read from Firebase, the server will render the data as an array for you.

Ivan C Myrvold
  • 680
  • 7
  • 23
  • Actually i think we can store our data in four forms --https://firebase.google.com/docs/database/ios/save-data Maybe i am wrong.. – Dravidian Jul 17 '16 at 10:52
  • 1
    Here is a link explaining Arrays in Firebase, and why there is no native support for arrays.[Best Practices: Arrays in Firebase] (https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html) – Ivan C Myrvold Jul 17 '16 at 12:21