F. Bar F. Bar - 1 month ago 7
Swift Question

Most efficient way of storing data which can be accessed and changed by all users

I'm currently in the process of learning both Swift and Parse and for the question I'm asking I'm going to use a simple up vote on a cell.

So I've got a table view controller which is populated by a query to a table on Parse. To do this I create a query on the relevant table and then store the bits of information into arrays e.g. an array for usernames, and text posts and object ID's:

var postGrabber: [PFObject] = [PFObject]()
var pSenderUsername: [String] = [String]()
var pPostBody: [String] = [String]()
var objectId: [String] = [String]()


I can then use the indexPath of a cell to get the relevant information from the arrays above.

Each cell also has a UIButton (for casting a vote as well as other information).

Like so...

To get the
indexPath
of which cell has been clicked I use:

let btnPos: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: btnPos)!
let rowToAction = indexPath.first!



As a side note, objectAtIndexPath(rowToAction) does not seem to work in Swift 3, does anyone know of an alternative?


From this point I'm a little unsure of the most efficient way of updating my Parse table's score attribute.

After looking at the Parse docs, I could potentially use a counter variable to save a score or an array.

Though, I think if that there could be syncronization issues in using a counter in the case that multiple users are trying to access the data at any one given time. (Unsure)

Is it possible that someone could share their way of doing such a task possibly so that the data from Parse can only be accessed by 1 user at any 1 given time to avoid such issues.

Answer

So you want to increment the numberOfUpVotes.

You can use

[post incrementKey:@"numberOfUpVotes"];
[post saveInBackground];

This will update the votes asynchronously, and the incrementKey method is atomic. Let's say we have 5 users clicking on the "up" button at the same time, the value for key "numberOfUpVotes" will be 5 in stead of 1.

Also, you can specify your increment about by :

[post incrementKey:@"numberOfUpVotes" byAmount:[NSNumber numberWithInt:2]]

But I don't think this is gonna happen in your use case :)

You can read this post from Parse:

https://parse.com/questions/concurrency-management-in-parse

or you can see my question:

iOS Parse.com updating objects

note: my code is in Objective-C, but it's pretty easy to convert that into Swift.

Comments