所以我想说我想将一个成员变量设置为null。
MyObject m = new MyObject();
m.setMyNumber(null);
编译器错误:无法将null转换为double 所以我想到了一个技巧。
MyObject m = new MyObject();
Double d = null;
m.setMyNumber(d);
感觉有点hackish,但编译器没有抛出任何错误 问题是,如果我调用m.getMyNumber()会发生什么。
答案 0 :(得分:0)
此编译错误消息表示MyObject
包含double myNumber
字段而非对象:Double myNumber
字段。
但是你不能用null
设置原始变量。只能将对象分配给null
。
问题是,如果我调用m.getMyNumber()会发生什么。
你甚至没有时间调用它。
只要Double d = null; m.setMyNumber(d);
被执行,NullPointerException
将被null
抛出,因为unboxed
不能double
成为override func viewDidAppear(_ animated: Bool) {
receivedFunc()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: #selector(ReceivedViewController.receivedFunc), for: UIControlEvents.valueChanged)
receivedTable.addSubview(refresher)
}
func receivedFunc() {
//
ref = Database.database().reference()
let currentUserID = Auth.auth().currentUser?.uid
refHandle = ref.child("users").child(currentUserID!).observe(.value, with: { (snapshot) in
if let userDict = snapshot.value as? [String: Any] {
if let requests = userDict["requests"] as? [String: String] {
print("processing requests")
self.userIDs.removeAll()
self.userNames.removeAll()
self.userImages.removeAll()
for request in requests {
if request.value == "received" {
self.refHandle = self.ref.child("users").child(request.key).observe(.value, with: { (snapshot) in
if let userDict = snapshot.value as? [String: Any] {
if let userName = userDict["name"] {
let storage = Storage.storage()
let storageRef = storage.reference(forURL: "gs://money-owelend.appspot.com")
let profilePhotoRef = storageRef.child(request.key + "profile_photo.jpg")
profilePhotoRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("couldn't download the image")
} else {
self.userNames.append(userName as! String)
self.userIDs.append(request.key)
self.userImages.append(UIImage(data: data!)!)
//
self.receivedTable.reloadData()
self.refresher.endRefreshing()
}
}
}
}
}, withCancel: { (error) in
print("error observing value \(error)")
})
}
}
// reload data here
}
}
}, withCancel: { (error) in
print("error observing value \(error)")
})
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userIDs.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellReceived", for: indexPath) as! ReceivedTableViewCell
cell.hiddenIDLabel.text = userIDs[indexPath.row]
cell.userName.text = userNames[indexPath.row]
cell.userImage.image = userImages[indexPath.row]
return cell
}
值。
JLS引用了这一点:
5.1.8。拆箱转换
在运行时,取消装箱转换过程如下:
...
如果r为null,则取消装箱转换会抛出NullPointerException
答案 1 :(得分:0)
您的代码在调用setMyNumber时会在运行时崩溃,因为无法将null
转换为double
。
答案 2 :(得分:0)
您将获得NullPointerException。 :)