greenline Xcode EXC_BAD_INSTRUCTION on NSUserDefaults Optional - xcode

I've been writing an app that involves using NSUserDefaults to store a few Int variables and it's been working fine. I thought I was finished and was doing some final testing and one of the first lines of code that I wrote, and that has been working consistently before, has failed me.
Apparently the green line error is supposed to occur if I try to unwrap an optional that has a value of nil, but this variable is still very much an optional
var savedTotalSeconds: Int? = userDefaults.objectForKey("totalSecondsKey") as Int?
Why would this possibly return an error? It was working fine before and I only changed things I thought were unrelated to it. In the app I have a button to remove this stored value via:
userDefaults.removeObjectForKey("totalSecondsKey")
What could possibly have gone wrong?

Try using 'as? Int' instead of 'as Int?'
The difference is that the first one tries, and might fail, at casting to Int. That failure will be captured in the optionality of the resulting variable.
The second one tries to coerce the object to 'Int?'.

Related

How do I set an NSTableColumn headerCell stringValue in swift?

The documentation makes it look as if it would be as easy as this:
var tc = NSTableColumn(identifier: "mycolumn")
tc.headerCell.stStringValue("foo")
The last line of code is a compile error, which I don't understand. On top of that I get a couple of different compile error message for this exact same line of code depending on what mood XCode seems to be in. I've seen the following compile errors:
AnyObject does not have a member named 'stStringValue'
Cannot convert the expression's type 'NSString' to type 'StringLiteralConvertible'
I get this when try setting a variable and putting that in there:
Cannot convert the expression's type 'String' to type 'String?!'
I get this when I try the "foo \(bar)" variant:
Could not find member 'convertFromStringInterpolationSegment'
Hilariously enough if I declare a variable with type String?! it says it Cannot convert the expression's type 'String?!' to type 'String?!'
I don't understand what is going on. Is this a bug?
If I try this in a playground, the playground actually wants to autocomplete with an extra argument, this format:
tc.headerCell.setStringValue("foo", resolvingEntities: false)
This has no compile time errors, but results in a seg fault at run time. This format is also not in the documentation.
I really have no idea what's going on and the error messages aren't helping.
I finally got this to work, despite the terrible error messages. The problem is that headerCell is typed as AnyObject, I had to cast it. The second problem was that in swift land it's a property, not a method.
This finally worked:
var tc = NSTableColumn(identifier: "mycolumn")
let hc = column1.headerCell as NSTableHeaderCell
hc.stringValue = "foo"

How to force a raw value of 7 into a UIViewAnimationCurve enum?

The key UIKeyboardAnimationCurveUserInfoKey in the userInfo dictionary of a UIKeyboardWillShowNotification contains an Int with the value 7.
Now I need to pass this Int into UIView.setAnimationCurve(<here>). I tried to create the required UIViewAnimationCurve enum like this UIViewAnimationCurve(rawValue: 7). Because the raw value 7 is undocumented, the result is always nil.
It works fine this way in Objective-C. Any idea how to get this animation curve from the notification into a UIView animation using Swift?
Update:
As pointed out by Martin, this is no longer a problem since Xcode 6.3.
From the Xcode 6.3 Release Notes:
Imported NS_ENUM types with undocumented values, such as UIViewAnimationCurve, can now be converted from their raw integer values using the init(rawValue:) initializer without being reset to nil. Code that used unsafeBitCast as a workaround for this issue can be written to use the raw value initializer.
I think I figured it out, but I'm not sure if this is the way it's supposed to be done.
let animationCurve = unsafeBitCast(7, UIViewAnimationCurve.self)
UIView.setAnimationCurve(animationCurve)
Update: The solution contained in this question works as well.
var animationCurve = UIViewAnimationCurve.EaseInOut
NSNumber(integer: 7).getValue(&animationCurve)

Type mismatch error while reading lotus notes document in vb6

Am trying to read the lotus notes document using VB6.I can able to read the values of the but suddenly type mismatch error is throwed.When i reintialise the vb6 variable it works but stops after certain point.
ex; address field in lotus notes
lsaddress=ImsField(doc.address)
private function ImsField(pValue)
ImsField=pValue(0)
end function
Like this I am reading the remaining fields but at certain point the runtime error "13" type mismatch error throwed.
I have to manually reintialize by
set doc=view.getdocumentbykey(doclist)
The type mismatch error occurs for a certain field. The issue should be a data type incompatibility. Try to figure out which field causes the error.
Use GetItemValue() instead of short notation for accessing fields and don't use ImsField():
lsaddress=doc.GetItemValue("address")(0)
The type mismatch is occurring because you are encountering a case where pValue is not an array. That will occur when you attempt to reference a NotesItem that does not exist. I.e., doc.MissingItem.
You should not use the shorthand notation doc.itemName. It is convenient, but it leads to sloppy coding. You should use getItemValue as everyone else is suggesting, and also you should check to see if the NotesItem exists. I.e.,
if doc.hasItem("myItem") then
lsaddress=doc.getItemValue("myItem")(0)
end if
Notes and Domino are schema-less. There are no data integrity checks other than what you write yourself. You may think that the item always has to be there, but the truth is that there is nothing that will ever guarantee that, so it is always up to you to write your code so that it doesn't assume anything.
BTW: There are other checks that you might want to perform besides just whether or not the field exists. You might want to check the field's type as well, but to do that requires going one more level up the object chain and using getFirstItem instead of getItemValue, which I'm not going to get into here. And the reason, once again, is that Notes and Domino are schema-less. You might think that a given item must always be a text list, but all it takes is someone writing sloppy code in an one-time fix-it agent and you could end up having a document in which that item is numeric!
Checking your fields is actually a good reason (sometimes) to encapsulate your field access in a function, much like the way you have attempted to do. The reason I added "sometimes" above is that your code's behavior for a missing field isn't necessarily always going to be the same, but for cases where you just want to return a default value when the field doesn't exist you can use something like this:
lsaddress ImsField("address","")
private function ImsField(fieldName,defaultValue)
if doc.hasItem(fieldName) then
lsaddress=doc.getItemValue(fieldName)(0)
else
lsaddress=defaultValue
end if
end function
Type mismatch comes,
When you try to set values from one kind of datatype variable to different datatype of another variable.
Eg:-
dim x as String
Dim z as variant
z= Split("Test:XXX",":")
x=z
The above will through the error what you mentioned.
So check the below code...
lsaddress = ImsField(doc.address)
What is the datatype of lsaddress?
What is the return type of ImsField(doc.address)?
If the above function parameter is a string, then you should pass the parameter like (doc.address(0))

How does a DataObjects::SQLError object's .code correspond to the error issued by the database?

So I'm doing some business logic and want to run some code that goes like
select id from blah where foo = 1234 for update nolock
This code throws a DataMapper::SQLError when the corresponding row in blah is locked. This is desirable behavior; I would like to catch this error and use it to inform my application logic. But I want to re-throw any other SQL errors, because they're different than the case I'm programming for, and catching them in the same way would be wrong.
The error object returned has a string error message, and a numeric code (50463045). It seems like comparing on the numeric code would be great, but I don't want to embed the constant 50463045 in my code without some modicum of understanding of how the heck it was determined. Notably, the Postgres manual suggests that the error code for this state is 55P03, and that doesn't seem to be the same thing. I don't have any idea how much I can trust this magic number, and how to determine it except for experimentally, so I'm not really comfortable with using it.
How is the error code determined?
The Internet was distressingly unhelpful, since searching for stuff about DataObjects SQL errors seems to mostly return problems with other software raising the errors, not information on the errors themselves... but after locating the right source code and browsing around through the source code I finally located do_postgres.c:
void do_postgres_raise_error(VALUE self, PGresult *result, VALUE query) {
const char *message = PQresultErrorMessage(result);
char *sql_state = PQresultErrorField(result, PG_DIAG_SQLSTATE);
int postgres_errno = MAKE_SQLSTATE(sql_state[0], sql_state[1], sql_state[2], sql_state[3], sql_state[4]);
PQclear(result);
data_objects_raise_error(self, do_postgres_errors, postgres_errno, message, query, rb_str_new2(sql_state));
}
Notice how a 5-character state is passed to MAKE_SQLSTATE... and then also passed to data_objects_raise_error itself. I couldn't track down where MAKE_SQLSTATE is defined to figure out what crazy manipulations are going on to make this integer, but it appears I can just use the error object's .sqlstate property directly, and make my condition e.sqlstate == '55P03'.

Cannot access animate-properties in Clutter

I am trying to animate an actor in Clutter, but when I enter a property that exists, something goes wrong.
actor.animate( AnimationMode.LINEAR, 400, scale_x:2);
gives me this error
Clutter-WARNING **: Cannot bind property '\x83\xec\u0014\x89\xc6e\xa1\u000c': objects of type 'ClutterTexture' do not have this property
Looks like Unicode-characters to me.
However, when I enter a property that does NOT exist
actor.animate( AnimationMode.LINEAR, 400, thisdoesntwork:2);
I get an error that makes much more sense
Clutter-WARNING **: Cannot bind property 'thisdoesntwork': objects of type 'ClutterTexture' do not have this property
I get the exact same problem when I try this alternative approach:
actor.animate( AnimationMode.LINEAR, 400, "scale-x", 2);
How come all properties that actually exist get converted to some mess, and what can I do to get this to work?
You should be using 2.0 for the value, not 2. 2 is an integer, 2.0 is a double. Vala can't provide type safety for variadic methods, so you have to be careful.
As for why you're seeing the behavior you are for properties which exist, my guess is it has to do with the fact that 2 is a (32-bit) integer and 2.0 is a (64-bit) double. This is simplifying things a bit, and I don't know how much experience you have with C (probably not a lot, since this is the sort of mistake someone coming from a dynamically typed language would make), however... Clutter (well, va_arg) expects a double so it parses 64 bits of data, but you only provided 32 bits, so the first 32-bits of the next argument (NULL) are included. Now, when it starts trying to parse the next argument it starts from the wrong location (32-bits into the argument), so you get the the remainder of NULL and part of whatever garbage happened to be on the stack... Unsuprisingly, that doesn't just so happen to be 32-bits of 0s so when Clutter tests to see if the value it just read == NULL it isn't and Clutter thinks it's been given a pointer to an null-terminated array of characters (which is how strings are represented in C). It reads the data at that location, which just so happens to be \x83\xec\u0014\x89\xc6e\xa1\u000c, and checks to see if there is a property with that name. There isn't, so it emits the error message you saw.
Now, if you switch to using a property which doesn't exist, Clutter will parse the argument (the name of the property), notice that it doesn't exist (just like it did with the second property above), and emit an error.

Resources