PFQueryTableView Controller not loading custom Cells - xcode

Im working on an app and I would like it to populate the cells based on users who are within a set distance from the currentuser. For some reason the customcells are not being populated with the correct objects. The labels and images that are supposed to be retrieved are blank. All i get is a blank cell. I made sure i gave the cell identifier the correct name, and i also made sure to link the tableviewcontroller and the tablecellview to their respective classes,but still no luck.
first i created initializers:
class TableViewController: PFQueryTableViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currLocation: CLLocationCoordinate2D?
override init!(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.parseClassName = "User"
self.textKey = "FBName"
// self.imageKey = "pictureURL"
self.pullToRefreshEnabled = true
self.objectsPerPage = 10
self.paginationEnabled = true
}
Then in viewDidLoad i enabled location services:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 200
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
loadData()
println("location services enabled bruh")
}
}
Next i overrode the queryfortable function:
override func queryForTable() -> PFQuery! {
let query = PFQuery(className: "User")
if let queryLoc = currLocation {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: queryLoc.latitude, longitude: queryLoc.longitude), withinMiles: 50)
query.limit = 40
query.orderByAscending("createdAt")
println("\(queryLoc.latitude)")
return query
} else {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: 37.411822, longitude: -121.941125), withinMiles: 50)
query.limit = 40
query.orderByAscending("createdAt")
println("else statement")
return query
}
}
then the objectAtIndexPath function
override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject! {
var obj : PFObject? = nil
if indexPath.row < self.objects.count {
obj = self.objects[indexPath.row] as? PFObject
}
return obj
}
and lastly I returned the cell, but for some reason it does not work:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject?) -> PFTableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as TableViewCell
cell.userName?.text = object?.valueForKey("FBName") as? String
let userProfilePhotoURLString = object?.valueForKey("pictureURL") as? String
var pictureURL: NSURL = NSURL(string: userProfilePhotoURLString!)!
var urlRequest: NSURLRequest = NSURLRequest(URL: pictureURL)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (NSURLResponse response, NSData data,NSError error) -> Void in
if error == nil && data != nil {
cell.userImage?.image = UIImage(data: data)
}
}
cell.ratingsView?.show(rating: 4.0, text: nil)
return cell
}
ps, i have the number of sections set to 1, just didnt think that method would be useful to show here.

okay I found the issue! The issue was that I was trying to use PFQuery in order to retrieve a list of PFUsers. I found out that cannot be done using PFQuery infact PFUser has it's own query method for retrieving information from its users.
all i had to do was replace this line:
let query = PFQuery(className: "User")
with this:
let query = PFUser.query()

Related

Why am I getting a crash saying "Fatal Error: Array Index out of range"?

Hi I am trying to have an app that adds a point in a mapView, sends it to to a ViewController and when the user taps on a place in the tableView it should send back to the point in the mapView but this is where I get the error, my app crashes and I get "thread 1 exc_bad_instruction (code=exc_1386_invop subcode=0x0)" on the line that says:
let latitude = NSString(string: places[activePlace]["lat"]!).doubleValue
here is my code
if activePlace == -1 {
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
} else {
let latitude = NSString(string: places[activePlace]["lat"]!).doubleValue
let longitude = NSString(string: places[activePlace]["lon"]!).doubleValue
let coordinate = CLLocationCoordinate2DMake(latitude, longitude)
let latDelta:CLLocationDegrees = 0.01
let lonDelta:CLLocationDegrees = 0.01
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
self.Map.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = places[activePlace]["name"]
self.Map.addAnnotation(annotation)
//save data start
NSUserDefaults.standardUserDefaults().setObject(places, forKey: "places") // saves data to NSUserDefaults
//stop save data
}
and here is how active place is 'made'
var activePlace = -1
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
activePlace = indexPath.row
return indexPath
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "newPlace" {
activePlace = -1
}
#IBAction func addCurentLoc(sender: UIBarButtonItem) {
var newCoordinate2 = self.Map.userLocation.location!.coordinate;
var location = CLLocation(latitude: newCoordinate2.latitude, longitude: newCoordinate2.longitude)
//title = "new address"
//try change order start
let annotation = MKPointAnnotation()
self.Map.addAnnotation(annotation)
annotation.coordinate = newCoordinate2
annotation.title = title
annotation.coordinate = self.Map.userLocation.location!.coordinate;
CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) -> Void in
var title = ""
if (error == nil) {
if let p = placemarks?[0] {
var subThouroughfare:String = ""
var thouroughfare:String = ""
if p.subThoroughfare != nil {
subThouroughfare = p.subThoroughfare!
}
if p.thoroughfare != nil {
thouroughfare = p.thoroughfare!
}
title = "\(subThouroughfare) \(thouroughfare)"
}
}
if title == "" {
title = "Added \(NSDate())"
}
places.append(["name":title,"lat":"\(newCoordinate2.latitude)","lon":"\(newCoordinate2.longitude)"])
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate2
annotation.title = title
self.Map.addAnnotation(annotation)
}
self.Map.addAnnotation(annotation);
func mapView(mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
if(annotation is MKUserLocation){
return nil;
}
// let pinView: Void = mapView.addAnnotation(annotation);
let pinAnnotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier:"MyIdentifier");
return pinAnnotationView;
}
}
The print statement says this :
fatal error: Index out of range
(lldb)
how could I solve this issue? thanks !
"Fatal Error: Array Index out of range"?
This error occurs due to the places do not contain any object on index you are asking.
Example :
var places = [0,1,2,4]
// next line is crash because array do not contains any item on 5 index
places[5]
Try to check what you are using in this variable :activePlace

swift: refresh/reload table view did not work

i'm new in swift development, i added data in server tried to refresh tableviewcontroller with refreshcontrol function but value in table view didn't change.
class MainTableViewController: UITableViewController, UINavigationControllerDelegate {
#IBOutlet var sosTableView: UITableView!
var datas = [dataSos]()
override func viewDidLoad() {
super.viewDidLoad()
let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
spinningActivity.labelText = "Loading"
spinningActivity.detailsLabelText = "Please wait"
dispatch_async(dispatch_get_main_queue()) {
self.loadDataServer()
spinningActivity.hide(true)
self.sosTableView.reloadData()
}
//loadDataSos()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
var refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: Selector("refreshData"), forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl = refreshControl
}
Refresh func
func refreshData(){
dispatch_async(dispatch_get_main_queue()) {
self.loadDataServer()
self.sosTableView.reloadData()
}
refreshControl?.endRefreshing()
}
load server func
func loadDataServer(){
do {
let data = NSData(contentsOfURL: NSURL(string: "http://xxxx/scripts/xxx.php")!)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
//let NumberOfPersons = jsonResult.count
// **LOOP THROUGH THE JSON ARRAY**
for anItem in jsonResult as! [Dictionary<String, AnyObject>] {
let userId = anItem["userId"] as! String
let userName = anItem["firstName"] as! String
let userAddress = anItem["address"] as! String
let userDate = anItem["date"] as! String
let userLocation = anItem["location"] as! String
var userEvent = anItem["event"] as? String
let sosId = anItem["sosId"] as! String
// do something with personName and personID
let imageUrl = NSURL(string:"http://xxx")
let imageData = NSData(contentsOfURL: imageUrl!)
if userEvent == nil{
userEvent = "Need Help"
}else if userEvent! == "1" {
userEvent! = "Thief"
}
else if userEvent! == "2" {
userEvent! = "Fire"
}
else{
userEvent! = "Healthy Issue"
}
//print(personName)
if imageData == nil{
let photo1 = UIImage(named: "defaultPhoto")!
let data1 = dataSos(userId: userId, name: userName, location: userLocation, address: userAddress, event: userEvent!, date: userDate, photo: photo1, sosId: sosId)
self.datas += [data1]
}
else{
let photo1 = UIImage(data: imageData!)
//let photo1 = UIImage(named: "defaultPhoto")
let data1 = dataSos(userId: userId, name: userName, location: userLocation, address: userAddress, event: userEvent!, date: userDate, photo: photo1, sosId: sosId)
self.datas += [data1]
}
}
} catch let error as NSError {
print(error)
}
// }
}
Update: table view data source
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// warning Incomplete implementation, return the number of rows
return datas.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MainTableViewCell
// Configure the cell...
let data0 = datas[indexPath.row]
cell.nameLabel.text = data0.name
cell.locationLabel.text = data0.location
cell.addressTextView.text = data0.address
cell.eventLabel.text = data0.event
cell.dateLabel.text = data0.date
cell.photoLabel.image = data0.photo
self.roundingUIView(cell.photoLabel, cornerRadiusParam: 35)
return cell
}
Ok, I just understood that you're inheriting for UITableViewController, therefor you already have tableView property inherited from it. The table view from this property has already set delegate and dataSource to your controller, but not for your custom sosTableView. You should replace your custom sosTableView with inherited tableView property and then everything gonna work as you're expecting.

Append FMDB SQLite results to Swift array

I'm trying to append results from a FMDB SQLite query to a Swift array. The error I'm getting in XCode is 'value of option type 'String?' not unwrapped.'
Swapping out the line below in the while loop, the FMDB results can be printed to console OK, so no problems there.
println(results_lab_test?.stringForColumn("lab_test"))
New to XCode, so be kind...
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tests_label: UILabel!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var arrayData:[String] = []
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as! String
databasePath = docsDir.stringByAppendingPathComponent("vmd_db.db")
let myDatabase = FMDatabase(path: databasePath as String)
if myDatabase.open(){
let query_lab_test = "SELECT lab_test FROM lab_test"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
var multiLineString = join("\n", arrayData)
tests_label.text = multiLineString
tests_label.numberOfLines = 0
tests_label.lineBreakMode = NSLineBreakMode.ByWordWrapping
tests_label.sizeToFit()
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Working Code thanks to #skypecakes:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tests_label: UILabel!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as! String
databasePath = docsDir.stringByAppendingPathComponent("vmd_db.db")
let myDatabase = FMDatabase(path: databasePath as String)
if myDatabase.open(){
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
}
}
println(arrayData)
myDatabase.close()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
It seems like
results_lab_test?.stringForColumn("lab_test")
returns a String?, which is an optional. Your array is defined as an array of "String" items, so you can't put a "String?" inside it.
Try this:
if let resultString = results_lab_test?.stringForColumn("lab_test")
arrayData.append(resultString)
Note that in general it is good practice to unwrap all of your optionals with "if let" instead of assuming that they are populated. So everywhere you have a question mark (e.g. results_lab_test?.stringForColumn), you can use "if let".
If you're using XCode 7 with Swift 2.0, this would be a good case for the "guard let" statement, which provides a convenient syntax to abort your code if an optional returns null:
guard let queryResults = results_lab_test else return
while queryResults.next() == true {
if let resultString = queryResults.stringForColumn("lab_test")
arrayData.append(resultString)
}
This test worked for me (table has 2 rows, and printing the array prints 2 rows), in case it helps you:
import UIKit
import FMDB
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
if let myDatabase = makeSqlDB()
{
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true
{
if let resultString = results_lab_test?.stringForColumn("lab_test")
{
arrayData.append(resultString)
}
}
println(arrayData)
myDatabase.close()
}
}
private func makeSqlDB()->FMDatabase?
{
let database = FMDatabase(path: String())
if !database.open() {
println("Unable to open database")
return nil
}
if !database.executeUpdate("create table lab_test(lab_test text)", withArgumentsInArray: nil) {
println("create table failed: \(database.lastErrorMessage())")
}
if !database.executeUpdate("insert into lab_test (lab_test) values (?)", withArgumentsInArray: ["test1"]) {
println("insert 1 table failed: \(database.lastErrorMessage())")
}
if !database.executeUpdate("insert into lab_test (lab_test) values (?)", withArgumentsInArray: ["test2"]) {
println("insert 2 table failed: \(database.lastErrorMessage())")
}
return database
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Drag and Drop to NSArrayController

I am struggling to pass a variable received from a drag and drop (file from finder onto NSView) to a NSArrayController in AppDelegate.
NSView receives the drag and drop:
class MyView:NSView, NSDraggingDestination {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
let fileTypes = ["jpg", "jpeg", "bmp", "tif", "TIF"]
var fileTypeIsOk = false
var droppedFilePath = ""
required init?(coder: NSCoder) {
let types = [NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF]
super.init(coder: coder)
registerForDraggedTypes(types)
}
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(sender) == true {
fileTypeIsOk = true
return .Every
} else {
fileTypeIsOk = false
println("Dropped images rejected.")
return .None
}
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
var go = false
if let board = sender.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray {
for indexFile in 0...board.count-1 {
println("Files dropped \(board[indexFile])")
//-> pass the variable board[indexFile] or board[] to NSArrayController
go = true
}
}
return go
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
var go = false
var foundExtension = 0
var numberOfFiles = 0
if let board = drag.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray {
numberOfFiles = board.count
for indexFile in 0...numberOfFiles-1 {
if let url = NSURL(fileURLWithPath: (board[indexFile] as! String)) {
let suffix = url.pathExtension!
for ext in fileTypes {
if ext.lowercaseString == suffix {
++foundExtension
break
}
}
}
}
}
if foundExtension == numberOfFiles {
println("Dropped files have valid extension.")
go = true
} else {
println("At least one file dropped has an invalid extension.")
}
return go
}
}
in AppDelegate, I have set up an NSArrayController (pointing to data[] at the moment but I don't know how to populate data[] from board[])
func numberOfRowsInTableView(aTableView: NSTableView) -> Int {
return data.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var cellView: NSTableCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
println("Reload Array")
if tableColumn!.identifier == "fileNameColumn" {
cellView.imageView!.image = NSImage(named: "GreenCircle")
cellView.textField!.stringValue = data[row]
return cellView
}
...
thank you for your help
Call the "- (void)addObjects:(NSArray *)objects;" method on your NSArrayController and pass it board:
[self.myArrayController addObjects:board];
It worked by adding in NSView: performDragOperation:
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
then I can reach the 'data' variable using appDelegate.data.

You need to specify a parseClassName for the PFQueryTableViewController

I created a tableViewcontroller and assigned it the custom class: PFQueryTableViewController in story board. I then also gave it the parseClassName "userMessage" and for some reason when i try to run the application I always get the same error message: NSInternalInconsistencyException', reason: 'You need to specify a parseClassName for the PFQueryTableViewController.
I dont understand why I am getting this error because I explicitly gave the class a parseClassName.
Here is my associated code for the PFQueryTabletableViewController:
import UIKit
import CoreLocation
import Parse
class TableViewController: PFQueryTableViewController, CLLocationManagerDelegate {
let userMessages = ["blah blahh blahhh", "Beep Beep Boop", "Beep Beep Bobbity boop"]
let locationManager = CLLocationManager()
var currLocation: CLLocationCoordinate2D?
override init!(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.parseClassName = "userMessage"
self.textKey = "text"
self.pullToRefreshEnabled = true
self.objectsPerPage = 40
}
private func alert(message: String){
let alert = UIAlertController(title: "Uh-OH", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
let settings = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default) {(action) -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
return
}
alert.addAction(settings)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 120
self.tableView.rowHeight = 120
locationManager.desiredAccuracy = 100
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
alert("Cannot fetch your location!!")
}
override func queryForTable() -> PFQuery! {
let query = PFQuery(className: "Messages")
if let queryLoc = currLocation {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: queryLoc.latitude, longitude: queryLoc.longitude), withinMiles: 1)
query.limit = 40
query.orderByDescending("createdAt")
}else {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: 37.41182, longitude: -121.941125), withinMiles: 1)
query.limit = 40
query.orderByDescending("createdAt")
}
return query
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
locationManager.stopUpdatingLocation()
if(locations.count > 0) {
let location = locations[0] as CLLocation
println(location.coordinate)
currLocation = location.coordinate
} else {
alert("Cannot fetch your loation")
}
}
override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject! {
var obj : PFObject? = nil
if(indexPath.row < self.objects.count) {
obj = self.objects[indexPath.row] as? PFObject
}
return obj
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userMessages.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
cell.messageText.text = object.valueForKey("text") as? String
cell.messageText.numberOfLines = 0
let views = object.valueForKey("count") as Int
cell.numberOfViewsLabel.text = "\(views)"
cell.numberOfViewsLabel.text = "\((indexPath.row + 1) * 5)"
return cell
}
func addToViews(sender: AnyObject) {
let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
let object = objectAtIndexPath(hitIndex)
object.incrementKey("count")
object.saveInBackgroundWithBlock { (Bool, NSError) -> Void in
//blahhh
}
self.tableView.reloadData()
}
}
`
parseClassName is a readonly variable and is only used when subclassing PFObject.
https://parse.com/docs/ios/api/Classes/PFObject.html#//api/name/parseClassName
The class name of the object.
#property (strong, readonly) NSString *parseClassName
Declared In
PFObject.h
Obj-C
#implementation MYGame
#dynamic title;
+ (NSString *)parseClassName {
return #"Game";
}
#end
Swift
class MYGame: PFObject {
class func parseClassName() -> String! {
return "Game"
}
}
In my case I had used a storyboard and needed to create an initWithCoder: method in my PFQueryTableViewController subclass. The template pointed to in the Parse.com docs lacks this method, but the first comment following the example does include an example implementation: https://gist.github.com/jamesyu/ba03c1a550f14f88f95d#gistcomment-74202
The message "You need to specify a parseClassName for the PFQueryTableViewController" is being generated because none of the methods are setting the PFQueryTableViewController's parseClassName property. You'll note that the property is defined quite plainly in the initWithStyle: method example provided in the docs. But, that method won't be called if the view is loaded via a storyboard: for that you'll need to set parseClassName in the initWithCoder: method.
Also, don't confuse subclassing a PFQueryTableViewController for a PFObject. For a PFObject you need to create a class method called parseClassName and also register the subclass before calling [Parse setApplicationId:aid clientKey:ckey]. You don't do those things for a PFQueryTableViewController or any of the other ParseUI view controllers. They rely on one or more of the init methods.

Resources