1

I wanna subclass the PFUser object in swift. I also want to declare my own variables. The Parse documentation on subclassing do not cover PFUser at this point.

Parse documentation on subclassing PFObject:

class Armor : PFObject, PFSubclassing {
    class func load() {
       self.registerSubclass()
    }
    class func parseClassName() -> String! {
       return "Armor"
    }
}
0xRLA
  • 3,279
  • 4
  • 30
  • 42

2 Answers2

9

BridgingHeader.h:

#import <Parse/Parse.h>
#import <Parse/PFObject+Subclass.h>

User.swift:

import Foundation

class User : PFUser, PFSubclassing {

override class func load() {
    self.registerSubclass()
}

//My variables
dynamic var firstname: String
dynamic var lastname: String

}

DONT´T include this snippet when subclassing PFUser:

class func parseClassName() -> String! {
    return "User"
}
0xRLA
  • 3,279
  • 4
  • 30
  • 42
  • 1
    @NSManaged is specifically for Core Data. Can't you just use `dynamic` now that we have it in swift? – Nick Aug 20 '14 at 00:43
  • Nick, no but they´re working on it: https://www.parse.com/questions/pfsubclassing-in-swift – 0xRLA Aug 20 '14 at 17:25
  • 1
    That's pretty old (i.e. before the `dynamic` keyword was added to Swift) – Nick Aug 20 '14 at 18:06
  • 2
    I case someone don´t get the dynamic keyword to work, use @NSManaged instead. – 0xRLA Sep 08 '14 at 14:03
  • Do I need to use optional mark? Otherwise xcode complaints about my subclass not having any initializers – chrs Oct 08 '14 at 20:30
  • chrs. Yes, or use ! if you´re certain that your variable will have a value. When using ! you also don´t need to unwrap before using the variable. – 0xRLA Oct 09 '14 at 10:15
  • With 8.1SDK this worked for me even without the `dynamic` keyword. – mikey Jan 07 '15 at 13:56
  • Also if you are calling `self.registerSubclass()` in `load()` there is no need to call `User.registerSubclass()` in the AppDelegate. – mikey Jan 07 '15 at 13:57
8

In Swift 2.0 You not need to implement PFSubclassing Protocol for Subclassing PFUser.

Just create normal subclass like this;

class ParseUser: PFUser {

    @NSManaged var name: String?
    @NSManaged var surname: String?
    @NSManaged var phoneNumber: String?

    override class func initialize() {
        struct Static {
            static var onceToken : dispatch_once_t = 0;
        }
        dispatch_once(&Static.onceToken) {
            self.registerSubclass()
        }
    }
emresancaktar
  • 1,507
  • 17
  • 25
  • Given the new best practice for the singleton pattern, can't we replace the `Static` struct with `static var onceToken : dispatch_once_t = 0` alone? – Scott H Nov 05 '15 at 00:18
  • What is @NSManaged? I dont want to use core data or a local store or something like that. – Ricardo Nov 14 '15 at 17:13