Application crashes while saving core data in iOS11 - objective-c

Works perfectly in iOS 10. After I updated my iOS to iOS11 the application is crashing while saving data to core data with an exception.
I have used RZVinyl framework for coredata
BOOL isSaved = [currentContext save:&saveErr];
Assertion failed: (moreParameters->mostRecentEntry ==
CFArrayGetValueAtIndex(stack, stackCount - 1)), function
NSKeyValuePopPendingNotificationPerThread, file
/BuildRoot/Library/Caches/com.apple.xbs/Sources/Foundation_Sim/Foundation-1444.12/EO.subproj/NSKeyValueObserving.m, line 933.
0 libsystem_kernel.dylib 0x00000001826fd348 __pthread_kill + 8
1 libsystem_pthread.dylib 0x0000000182811354 pthread_kill$VARIANT$mp + 396
2 libsystem_c.dylib 0x000000018266cfd8 abort + 140
3 libsystem_c.dylib 0x0000000182640abc basename_r + 0
4 Foundation 0x00000001834f1a9c -[NSRunLoop+ 178844 (NSRunLoop) runUntilDate:] + 0
5 Foundation 0x00000001834df538 NSKeyValueDidChange + 436
6 Foundation 0x0000000183597ae4 NSKeyValueDidChangeWithPerThreadPendingNotifications + 140
7 CoreData 0x00000001854107c8 -[NSManagedObject didChangeValueForKey:] + 120
8 CoreData 0x0000000185416358 -[NSManagedObject+ 844632 (_NSInternalMethods) _updateFromRefreshSnapshot:includingTransients:] + 692
9 CoreData 0x000000018542e054 -[NSManagedObjectContext+ 942164 (_NestedContextSupport) _copyChildObject:toParentObject:fromChildContext:] + 652
10 CoreData 0x000000018542e4bc -[NSManagedObjectContext+ 943292 (_NestedContextSupport) _parentProcessSaveRequest:inContext:error:] + 804
11 CoreData 0x000000018542f3f0 __82-[NSManagedObjectContext+ 947184 (_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 580
12 CoreData 0x0000000185431644 internalBlockToNSManagedObjectContextPerform + 92
13 libdispatch.dylib 0x0000000182569048 _dispatch_client_callout + 16
14 libdispatch.dylib 0x0000000182571ae8 _dispatch_queue_barrier_sync_invoke_and_complete + 56
15 CoreData 0x000000018541dd10 _perform + 232
16 CoreData 0x000000018542f0e4 -[NSManagedObjectContext+ 946404 (_NestedContextSupport) executeRequest:withContext:error:] + 172
17 CoreData 0x0000000185387ff8 -[NSManagedObjectContext save:] + 2580
NSManagedObjectContext *currentContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[[currentContext userInfo] setObject:self forKey:kRZCoreDataStackParentStackKey];
[self performBlock:^{
BOOL hasChanges = [currentContext hasChanges];
if ( !hasChanges) {
RZVLogInfo(#"Managed object context %# does not have changes, not saving", self);
rzv_performSaveCompletionAsync(completion, nil);
return;
}
NSError *saveErr = nil;
BOOL isSaved = [currentContext save:&saveErr];
if ( !isSaved) {
RZVLogError(#"Error saving managed object context context %#: %#", self, saveErr);
rzv_performSaveCompletionAsync(completion, saveErr);
}
}];

Had the same thing right now and was looking for an answer when I came across your question.
Without any answers to be found I did some in-depth investigation and found the cause (at least in my case).
It turned out that one of the object's relationships was observing KV changes to update the object regarding changes to it's values, and it was also updating a change to the value of the relationship.
That triggered and update on the Object, which caused the relationship to updated with a change, and so on and so forth...
This recursion in KVO caused a crash.
Make sure that if you are observing changes via willChangeValue and didChangeValue to update your relationship regarding this change, don't update if the observer is the one being set.
Does that make sense for you?
Let me know if this is the case and you need a code sample to understand this very confusing answer.
UPDATE:
I know my answer is quite confusing and vague, so I'll add an example.
Consider the following.
We have two example classes which has relationship to each other (i.e reverse relationship):
class A: NSManagedObject {
#NSManaged var id: NSNumber!
#NSManaged var title: String?
#NSManaged var b: B!
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
b?.willChangeValue(forKey: "a")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
b?.didChangeValue(forKey: "a")
}
}
class B: NSManagedObject {
#NSManaged var id: NSNumber!
#NSManaged var name: String?
#NSManaged var date: Date?
#NSManaged var a: A!
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
a?.willChangeValue(forKey: "b")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
a?.didChangeValue(forKey: "b")
}
func setNewA(_ newA: A) {
newA.b = self
a = newA
}
}
We use willChangeValue and didChangeValue in each class to notify it's relationship regarding changes in itself.
Now consider the following code:
let b = B(context: context)
let a = A(context: context)
b.setNewA(a)
We use the setNewA function to set the reverse reference.
In the function, first b assigns itself to a.b for the reverse reference and then sets self.a reference.
At this point, a already knows about b.
The later will cause willChangeValue and didChangeValue on b to be called (as we set a). Then a will pick up the update and notify b.
From here on, try can guess how it continues.
This was pretty much what happened to me, with a few minor differences.
I overrode these functions because I am using a NSFetchedResultsController and I needed to pick up on changes in the relationships to update my UI.
It threw me in a loop that caused the crash.
At the end, the fix was rather simple. A was modified to be:
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
guard key != "b" else { return }
b?.willChangeValue(forKey: "a")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
guard key != "b" else { return }
b?.didChangeValue(forKey: "a")
}
and B was modified the same way, to be:
override func willChangeValue(forKey key: String) {
super.willChangeValue(forKey: key)
guard key != "a" else { return }
a?.willChangeValue(forKey: "b")
}
override func didChangeValue(forKey key: String) {
super.didChangeValue(forKey: key)
guard key != "a" else { return }
a?.didChangeValue(forKey: "b")
}
This prevents each from updating the other once the relationship itself is set (which is redundant, as each is already notified once one of it's properties is set), thus breaking the cycle.
Again, this was the case on my end and this is what fixed it.
Don't know if you're experiencing the issue due to the same reason, but hopefully it'll give you an idea where to look.
Hope it's easier to understand now.
If you're still having trouble understanding, share some code or contact me directly and I'll try and help.

Related

'unrecognized selector' for category method on SpriteKit class [duplicate]

I'm creating a game with SpriteKit, that has collision between 2 bodies. After setting up the bodies, I've implemented the didBegin(_contact:) moethod as shown below:
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == 0 && contact.bodyB.categoryBitMask == 1 {
gameOver()
}
}
and it worked perfectly.
Later, while inspecrting the documentation for this method, I found the following:
The two physics bodies described in the contact parameter are not passed in a guaranteed order.
So to be on the safe side, I've extended the SKPhysicsContact class with a function the swaps the categoryBitMask between both bodies, as following:
extension SKPhysicsContact {
func bodiesAreFromCategories(_ a: UInt32, and b: UInt32) -> Bool {
if self.bodyA.categoryBitMask == a && self.bodyB.categoryBitMask == b { return true }
if self.bodyA.categoryBitMask == b && self.bodyB.categoryBitMask == a { return true }
return false
}
}
The problem is that when the function gets called, the app crashes, and I get the following error:
2017-07-18 13:44:18.548 iSnake Retro[17606:735367] -[PKPhysicsContact bodiesAreFromCategories:and:]: unrecognized selector sent to instance 0x60000028b950
2017-07-18 13:44:18.563 iSnake Retro[17606:735367] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PKPhysicsContact bodiesAreFromCategories:and:]: unrecognized selector sent to instance 0x60000028b950'
This apparently is a bug, as answered here:
https://stackoverflow.com/a/33423409/6593818
The problem is, the type of contact is PKPhysicsContact (as you've noticed), even when you explicitly tell it to be an SKPhysicsContact, and the extension is on SKPhysicsContact. You'd have to be able to make an extension to PKPhysicsContact for this to work. From this logic, we can say that no instance methods will work in SKPhysicsContact extensions at the moment. I'd say it's a bug with SpriteKit, and you should file a radar. Class methods still work since you call them on the class itself.
In the meantime, you should be able to move that method into your scene or another object and call it there successfully.
For the record, this is not a Swift-specific problem. If you make the same method in an Objective-C category on SKPhysicsContact you'll get the same crash.
You can submit a bug report to apple:
https://developer.apple.com/bug-reporting/
And report it to the community:
https://openradar.appspot.com/search?query=spritekit
However, what you really want to do with your code is to add the category masks together. And then check for the sum (2 + 4 and 4 + 2 always equals 6, regardless of bodyA and bodyB order).
This is how you get unique contacts, if you set up your masks correctly in powers of two (2, 4, 8, 16, etc)
SKPhysicsContact is a wrapper class to PKPhysicsContact, you are extending SKPhysicsContact but in reality you need to extend PKPhysicsContact (Which you can't do)
To preserve order in your contact methods, just do:
let bodyA = contact.bodyA.categoryBitMask <= self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
let bodyB = contact.bodyA.categoryBitMask > self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
This way when you need to check for a specific node, you know what node to hit, so
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == 0 && contact.bodyB.categoryBitMask == 1 {
gameOver()
}
}
Becomes
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA.categoryBitMask <= self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
let bodyB = contact.bodyA.categoryBitMask > self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
if bodyA.categoryBitMask == 0 && bodyB.categoryBitMask == 1 {
gameOver()
}
}
You can then add to your code since you now know the individual bodies.
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA.categoryBitMask <= self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
let bodyB = contact.bodyA.categoryBitMask > self.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB
if bodyA.categoryBitMask == 0 && bodyB.categoryBitMask == 1 {
gameOver()
//since I know bodyB is 1, let's add an emitter effect on bodyB.node
}
}
BTW, for people who see this answer, categoryBitMask 0 should not be firing any contacts, you need some kind of value in it to work. This is a bug that goes beyond the scope of the authors question, so I left it at 0 and 1 to since that is what his/her code is doing and (s)he is claiming it works.

Generate a tree of structs with testing/quick, respecting invariants

I have a tree of structs which I'd like to test using testing/quick, but constraining it to within my invariants.
This example code works:
var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
type X struct {
HasChildren bool
Children []*X
}
func TestSomething(t *testing.T) {
x, _ := quick.Value(reflect.TypeOf(X{}), rnd)
_ = x
// test some stuff here
}
But we hold HasChildren = true whenever len(Children) > 0 as an invariant, so it'd be better to ensure that whatever quick.Value() generates respects that (rather than finding "bugs" that don't actually exist).
I figured I could define a Generate function which uses quick.Value() to populate all the variable members:
func (X) Generate(rand *rand.Rand, size int) reflect.Value {
x := X{}
throwaway, _ := quick.Value(reflect.TypeOf([]*X{}), rand)
x.Children = throwaway.Interface().([]*X)
if len(x.Children) > 0 {
x.HasChildren = true
} else {
x.HasChildren = false
}
return reflect.ValueOf(x)
}
But this is panicking:
panic: value method main.X.Generate called using nil *X pointer [recovered]
And when I change Children from []*X to []X, it dies with a stack overflow.
The documentation is very thin on examples, and I'm finding almost nothing in web searches either.
How can this be done?
Looking at the testing/quick source code it seems that you can't create recursive custom generators and at the same time reuse the quick library facilities to generate the array part of the struct, because the size parameter, that is designed to limit the number of recursive calls, cannot be passed back into quick.Value(...)
https://golang.org/src/testing/quick/quick.go (see around line 50)
in your case this lead to an infinite tree that quickly "explodes" with 1..50 leafs at each level (that's the reason for the stack overflow).
If the function quick.sizedValue() had been public we could have used it to accomplish your task, but unfortunately this is not the case.
BTW since HasChildren is an invariant, can't you simply make it a struct method?
type X struct {
Children []*X
}
func (me *X) HasChildren() bool {
return len(me.Children) > 0
}
func main() {
.... generate X ....
if x.HasChildren() {
.....
}
}

GoLang, REST, PATCH and building an UPDATE query

since few days I was struggling on how to proceed with PATCH request in Go REST API until I have found an article about using pointers and omitempty tag which I have populated and is working fine. Fine until I have realized I still have to build an UPDATE SQL query.
My struct looks like this:
type Resource struct {
Name *string `json:"name,omitempty" sql:"resource_id"`
Description *string `json:"description,omitempty" sql:"description"`
}
I am expecting a PATCH /resources/{resource-id} request containing such a request body:
{"description":"Some new description"}
In my handler I will build the Resource object this way (ignoring imports, ignoring error handling):
var resource Resource
resourceID, _ := mux.Vars(r)["resource-id"]
d := json.NewDecoder(r.Body)
d.Decode(&resource)
// at this point our resource object should only contain
// the Description field with the value from JSON in request body
Now, for normal UPDATE (PUT request) I would do this (simplified):
stmt, _ := db.Prepare(`UPDATE resources SET description = ?, name = ? WHERE resource_id = ?`)
res, _ := stmt.Exec(resource.Description, resource.Name, resourceID)
The problem with PATCH and omitempty tag is that the object might be missing multiple properties, thus I cannot just prepare a statement with hardcoded fields and placeholders... I will have to build it dynamically.
And here comes my question: how can I build such UPDATE query dynamically? In the best case I'd need some solution with identifying the set properties, getting their SQL field names (probably from the tags) and then I should be able to build the UPDATE query. I know I can use reflection to get the object properties but have no idea hot to get their sql tag name and of course I'd like to avoid using reflection here if possible... Or I could simply check for each property it is not nil, but in real life the structs are much bigger than provided example here...
Can somebody help me with this one? Did somebody already have to solve the same/similar situation?
SOLUTION:
Based on the answers here I was able to come up with this abstract solution. The SQLPatches method builds the SQLPatch struct from the given struct (so no concrete struct specific):
import (
"fmt"
"encoding/json"
"reflect"
"strings"
)
const tagname = "sql"
type SQLPatch struct {
Fields []string
Args []interface{}
}
func SQLPatches(resource interface{}) SQLPatch {
var sqlPatch SQLPatch
rType := reflect.TypeOf(resource)
rVal := reflect.ValueOf(resource)
n := rType.NumField()
sqlPatch.Fields = make([]string, 0, n)
sqlPatch.Args = make([]interface{}, 0, n)
for i := 0; i < n; i++ {
fType := rType.Field(i)
fVal := rVal.Field(i)
tag := fType.Tag.Get(tagname)
// skip nil properties (not going to be patched), skip unexported fields, skip fields to be skipped for SQL
if fVal.IsNil() || fType.PkgPath != "" || tag == "-" {
continue
}
// if no tag is set, use the field name
if tag == "" {
tag = fType.Name
}
// and make the tag lowercase in the end
tag = strings.ToLower(tag)
sqlPatch.Fields = append(sqlPatch.Fields, tag+" = ?")
var val reflect.Value
if fVal.Kind() == reflect.Ptr {
val = fVal.Elem()
} else {
val = fVal
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
sqlPatch.Args = append(sqlPatch.Args, val.Int())
case reflect.String:
sqlPatch.Args = append(sqlPatch.Args, val.String())
case reflect.Bool:
if val.Bool() {
sqlPatch.Args = append(sqlPatch.Args, 1)
} else {
sqlPatch.Args = append(sqlPatch.Args, 0)
}
}
}
return sqlPatch
}
Then I can simply call it like this:
type Resource struct {
Description *string `json:"description,omitempty"`
Name *string `json:"name,omitempty"`
}
func main() {
var r Resource
json.Unmarshal([]byte(`{"description": "new description"}`), &r)
sqlPatch := SQLPatches(r)
data, _ := json.Marshal(sqlPatch)
fmt.Printf("%s\n", data)
}
You can check it at Go Playground. The only problem here I see is that I allocate both the slices with the amount of fields in the passed struct, which may be 10, even though I might only want to patch one property in the end resulting in allocating more memory than needed... Any idea how to avoid this?
I recently had same problem. about PATCH and looking around found this article. It also makes references to the RFC 5789 where it says:
The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.
e.g:
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
This set of instructions should make it easier to build the update query.
EDIT
This is how you would obtain sql tags but you will have to use reflection:
type Resource struct {
Name *string `json:"name,omitempty" sql:"resource_id"`
Description *string `json:"description,omitempty" sql:"description"`
}
sp := "sort of string"
r := Resource{Description: &sp}
rt := reflect.TypeOf(r) // reflect.Type
rv := reflect.ValueOf(r) // reflect.Value
for i := 0; i < rv.NumField(); i++ { // Iterate over all the fields
if !rv.Field(i).IsNil() { // Check it is not nil
// Here you would do what you want to having the sql tag.
// Creating the query would be easy, however
// not sure you would execute the statement
fmt.Println(rt.Field(i).Tag.Get("sql")) // Output: description
}
}
I understand you don't want to use reflection, but still this may be a better answer than the previous one as you comment state.
EDIT 2:
About the allocation - read this guide lines of Effective Go about Data structures and Allocation:
// Here you are allocating an slice of 0 length with a capacity of n
sqlPatch.Fields = make([]string, 0, n)
sqlPatch.Args = make([]interface{}, 0, n)
With make(Type, Length, Capacity (optional))
Consider the following example:
// newly allocated zeroed value with Composite Literal
// length: 0
// capacity: 0
testSlice := []int{}
fmt.Println(len(testSlice), cap(testSlice)) // 0 0
fmt.Println(testSlice) // []
// newly allocated non zeroed value with make
// length: 0
// capacity: 10
testSlice = make([]int, 0, 10)
fmt.Println(len(testSlice), cap(testSlice)) // 0 10
fmt.Println(testSlice) // []
// newly allocated non zeroed value with make
// length: 2
// capacity: 4
testSlice = make([]int, 2, 4)
fmt.Println(len(testSlice), cap(testSlice)) // 2 4
fmt.Println(testSlice) // [0 0]
In your case, may want to the following:
// Replace this
sqlPatch.Fields = make([]string, 0, n)
sqlPatch.Args = make([]interface{}, 0, n)
// With this or simple omit the capacity in make above
sqlPatch.Fields = []string{}
sqlPatch.Args = []interface{}{}
// The allocation will go as follow: length - capacity
testSlice := []int{} // 0 - 0
testSlice = append(testSlice, 1) // 1 - 2
testSlice = append(testSlice, 1) // 2 - 2
testSlice = append(testSlice, 1) // 3 - 4
testSlice = append(testSlice, 1) // 4 - 4
testSlice = append(testSlice, 1) // 5 - 8
Alright, I think the solution I used back in 2016 was quite over-engineered for even more over-engineered problem and was completely unnecessary. The question asked here was very generalized, however we were building a solution that was able to build its SQL query on its own and based on the JSON object or query parameters and/or Headers sent in the request. And that to be as generic as possible.
Nowadays I think the best solution is to avoid PATCH unless truly necessary. And even then you still can use PUT and replace the whole resource with patched property/ies coming already from the client - i.e. not giving the client the option/possibility to send any PATCH request to your server and to deal with partial updates on their own.
However this is not always recommended, especially in cases of bigger objects to save some C02 by reducing the amount of redundant transmitted data. Whenever today if I need to enable a PATCH for the client I simply define what can be patched - this gives me clarity and the final struct.
Note that I am using a IETF documented JSON Merge Patch implementation. I consider that of JSON Patch (also documented by IETF) redundant as hypothetically we could replace the whole REST API by having one single JSON Patch endpoint and let clients control the resources via allowed operations. I also think the implementation of such JSON Patch on the server side is way more complicated. The only use-case I could think of using such implementation is if I was implementing a REST API over a file system...
So the struct may be defined as in my OP:
type ResourcePatch struct {
ResourceID some.UUID `json:"resource_id"`
Description *string `json:"description,omitempty"`
Name *string `json:"name,omitempty"`
}
In the handler func I'd decode the ID from the path into the ResourcePatch instance and unmarshall JSON from the request body into it, too.
Sending only this
{"description":"Some new description"}
to PATCH /resources/<UUID>
I should end up with with this object:
ResourcePatch
* ResourceID {"UUID"}
* Description {"Some new description"}
And now the magic: use a simple logic to build the query and exec parameters. For some it may seem tedious or repetitive or unclean for bigger PATCH objects, but my reply to this would be: if your PATCH object consists of more than 50% of the original resource' properties (or simply too many for your liking) use PUT and expect the clients to send (and replace) the whole resource instead.
It could look like this:
func (s Store) patchMyResource(r models.ResourcePatch) error {
q := `UPDATE resources SET `
qParts := make([]string, 0, 2)
args := make([]interface{}, 0, 2)
if r.Description != nil {
qParts = append(qParts, `description = ?`)
args = append(args, r.Description)
}
if r.Name != nil {
qParts = append(qParts, `name = ?`)
args = append(args, r.Name)
}
q += strings.Join(qParts, ',') + ` WHERE resource_id = ?`
args = append(args, r.ResourceID)
_, err := s.db.Exec(q, args...)
return err
}
I think there's nothing simpler and more effective. No reflection, no over-kills, reads quite good.
Struct tags are only visible through reflection, sorry.
If you don't want to use reflection (or, I think, even if you do), I think it is Go-like to define a function or method that "marshals" your struct into something that can easily be turned into a comma-separated list of SQL updates, and then use that. Build small things to help solve your problems.
For example given:
type Resource struct {
Name *string `json:"name,omitempty" sql:"resource_id"`
Description *string `json:"description,omitempty" sql:"description"`
}
You might define:
func (r Resource) SQLUpdates() SQLUpdates {
var s SQLUpdates
if (r.Name != nil) {
s.add("resource_id", *r.Name)
}
if (r.Description != nil) {
s.add("description", *r.Description)
}
}
where the type SQLUpdates looks something like this:
type SQLUpdates struct {
assignments []string
values []interface{}
}
func (s *SQLUpdates) add(key string, value interface{}) {
if (s.assignments == nil) {
s.assignments = make([]string, 0, 1)
}
if (s.values == nil) {
s.values = make([]interface{}, 0, 1)
}
s.assignments = append(s.assignments, fmt.Sprintf("%s = ?", key))
s.values = append(s.values, value)
}
func (s SQLUpdates) Assignments() string {
return strings.Join(s.assignments, ", ")
}
func (s SQLUpdates) Values() []interface{} {
return s.values
}
See it working (sorta) here: https://play.golang.org/p/IQAHgqfBRh
If you have deep structs-within-structs, it should be fairly easy to build on this. And if you change to an SQL engine that allows or encourages positional arguments like $1 instead of ?, it's easy to add that behavior to just the SQLUpdates struct without changing any code that used it.
For the purpose of getting arguments to pass to Exec, you would just expand the output of Values() with the ... operator.

Variable contains nil value in Swift 2

I declared a variable destinationID on top of my class. The first print shows the right content of the variable while the second one has a nil value.
Does anyone know what the problem is?
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate{
var destinationUserID = String()
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//Opzoeken wat het bijhorende ID is
let query = PFQuery(className:"_User")
query.whereKey("username", equalTo:selectedUsername)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
// Do something with the found object
for object in objects! {
self.destinationUserID = object.objectId!
print(self.destinationUserID)
}
print("try 1 : " + self.destinationUserID)
}
print("try 2 : " + self.destinationUserID)
}
}
The print("try 1... statement is inside the block. The print("try 2... is outside the block. The block is executed in the background which means that the search might not have completed when you get to print("try 2....

Operations based on user input Swift

long question, so bear with me...
I am attempting to create a bitcoin ticker and converter written in Swift. I am using the code below (bits not related to conversion are removed - let me know if I left out anything important)
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var USD: UITextField! //Amount of USD. Originally equals 1 bitcoin, can be changed by user.
#IBOutlet weak var BTC: UILabel! //Amount of bitcoins the entered amount of USD is worth. Originally 1.
func handler(response: NSURLResponse!, data : NSData!, error : NSError!) { //To fetch Bitcoin Price. This is functional.
if ((error) != nil) {
self.USD.text = "No Internet" // in case of error
} else {
var price = NSString(data:data, encoding:NSUTF8StringEncoding)
self.USD.text = price //set USD to be equal to price of 1 Bitcoin
}
override func viewDidLoad() {
//Sets up view
self.update() //Fetches Bitcoin Price. This works.
self.convert() //Begins convert method
var timer = NSTimer.scheduledTimerWithTimeInterval(120, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func convert() {
var url = NSURL(string:"https://api.bitcoinaverage.com/ticker/USD/last")
var request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:handler)
var data = NSData(contentsOfURL:url);
while true {
if USD.text != data {
BTC.text = USD.text / NSString(data:data, encoding:NSUTF8StringEncoding)// Attempts to determine amount of bitcoin the USD amount is worth. ERROR HERE!
}
}
On the line with the comment "ERROR HERE", I get the error
/Users/[My User]/Documents/dev/Newest Stuff/CryptoCoinTicker/CryptoCoinTicker/ViewController.swift:95:32: 'String' is not convertible to 'UInt8'
In case the code doesn't tell the story, I want BTC.text to change to be equal in value to the amount entered by the user in USD.text (so if a bitcoin is worth $500, and the user entered 250.00, BTC.text would say 0.5.
What do I need to do? Apologies for a (probably) basic question, I am but a newbie. Let me know if you ned more info.
Thanks in advance!
When you get that error, it usually means that you are trying to assign a wrong type to a variable or that you are using the wrong types for function parameters.
In your case, you are trying to divide two Strings. The compiler doesn't know what to do, since the division of Strings is not defined. You can only divide Int, Float and Double and you can't even mix them!
So for that line you can substitute this:
let value = NSString(string: USD.text).doubleValue / NSString(data:data, encoding:NSUTF8StringEncoding).doubleValue
BTC.text = "\(value)"
This first "converts" the USD.text to NSString and then converts both NSStrings to Doubles, which you can then divide.
It then creates a String from that value, which can be assigned to the BTC.text property.