I am trying to implement search function in my app that uses Parse and want to use reload data to sort PFObjects. My app can do reloadData() first time, but it returns "unexpectedly found nil while unwrapping an Optional value" after the first time. I have tried conducting reloadData in the mainThread and removing weak reference in my collectionView, but it still does not work. I attached my code below. Thank you in advance!
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
loadCollectionViewData()
}
//This method is also conducted when the user taps search button
func loadCollectionViewData(){
let ud = NSUserDefaults.standardUserDefaults()
var query = PFQuery(className: "Posts")
if ud.objectForKey("searchKeyFromVCKey") != nil{
//This is keyword the user puts in
var searchKey = ud.objectForKey("searchKeyFromVCKey") as! String
println("searchKey \(searchKey)")
if searchKey != "" {
//If a user is searching something...
query.whereKey("searchTag", containsString: searchKey.lowercaseString)
}}
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
postObject.removeAll(keepCapacity: false)
if let object = objects as? [PFObject] {
postObject = object
}
self.collectionView.reloadData() //This works the first time when I conduct loadCollectionViewData() in ViewDidLoad
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
ud.removeObjectForKey("searchKeyFromVCKey")
}
postObject = object
intopostObject = object!
– DDPWNAGEif (object == nil)
statement in there. – DDPWNAGE