Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from NSValue in Swift?

Tags:

ios

swift

nsvalue

Here's what I've tried so far

func onKeyboardRaise(notification: NSNotification) {
    var notificationData = notification.userInfo
    var duration = notificationData[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
    var frame = notificationData[UIKeyboardFrameBeginUserInfoKey]! as NSValue
    var frameValue :UnsafePointer<(CGRect)> = nil;
    frame.getValue(frameValue)
}

But I always seem to crash at frame.getValue(frameValue).

It's a little bit confusing because the documentation for UIKeyboardFrameBeginUserInfoKey says it returns a CGRect object, but when I log frame in the console, it states something like NSRect {{x, y}, {w, h}}.

like image 967
tambykojak Avatar asked Aug 02 '14 04:08

tambykojak


People also ask

What is NSNumber in Swift?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .

What is NSValue in Swift?

A simple container for a single C or Objective-C data item.

What is NSValue?

NSValue is a simple container for a single C or Objective-C data value. It can hold scalars and value types, as well as pointers and object IDs.


1 Answers

getValue() must be called with a pointer to an (initialized) variable of the appropriate size:

var frameValue = CGRect(x: 0, y: 0, width: 0, height: 0)
frame.getValue(&frameValue)

But it is simpler to use the convenience method:

let frameValue = frame.CGRectValue() // Swift 1, 2
let frameValue = frame.cgRectValue() // Swift 3
like image 196
Martin R Avatar answered Oct 14 '22 07:10

Martin R