Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

强制类型转换 #58

Closed
izhexi opened this issue Jul 7, 2015 · 6 comments
Closed

强制类型转换 #58

izhexi opened this issue Jul 7, 2015 · 6 comments

Comments

@izhexi
Copy link

izhexi commented Jul 7, 2015

你好,我在JS中拿到OC 的 NSNumber 类型,在进行 NSNumber -->NSString的转换中,该怎么转换?
在 tableView_cellForRowAtIndexPath 方法中:
num 是一个在 OC 中的 NSNumber 对象。
var num = self.dataSource()[indexPath.row].sringValue();
cell.textLabel().setText(num +"js");
报错:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'js exception: TypeError: undefined is not an object (evaluating 'num.__c')'。
js的强制转换 String(value),不起作用。

@bang590
Copy link
Owner

bang590 commented Jul 7, 2015

对OC返回的NSString/NSArray/NSDictionary调用toJS()方法会得到JS里对应的类型:

var num = self.dataSource()[indexPath.row].sringValue();.toJS();
cell.textLabel().setText(num +"js");

详见wiki https://github.com/bang590/JSPatch/wiki/Base-usage

@albert438
Copy link
Contributor

NSNumber回传到JS中是JS里的Number类型,转成字符串可以用JS中的toString()方法。

@albert438
Copy link
Contributor

    var num = self.dataSource().objectAtIndex(indexPath.row())
    cell.textLabel().setText(num + "js")

@bang590
Copy link
Owner

bang590 commented Jul 7, 2015

@albert438 没注意到它这里原来是number,其实不用toString()也能得出结果:1+"JS"=="1JS"

@albert438
Copy link
Contributor

@bang590 👍 已改正。
他这里报错的原因是在这里,self.dataSource()[indexPath.row],self.dataSource()返回的是一个NSMutableArray对象,所以在JS中不能用中括号。楼主要用中括号的话要转成JS对象:

 var jsArray    = self.dataSource().toJS()
 cell.textLabel().setText(jsArray[indexPath.row()] + "JS")

@izhexi
Copy link
Author

izhexi commented Jul 8, 2015

确实是中括号的问题 ,使用中括号后,取出来的值为 undefined。虽不报错,但是拿不到正确类型。js 语法与 OC 混用了。问题已经解决一下两种都可以:

var jsArray = self.dataSource().toJS()
cell.textLabel().setText(jsArray[indexPath.row()] + "JS")

var num = self.dataSource().objectAtIndex(indexPath.row())
cell.textLabel().setText(num + "js")

@bang590 bang590 closed this as completed Jul 8, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants