Swift 4中如何从Parse的Score类PFObject获取username与score字段
username and score Fields from a Parse PFObject in Swift 4 Hey there! Let's walk through how to pull the username and score values from your Score class PFObject in Swift 4. There are two common approaches, depending on whether you want quick access or type-safe, scalable code.
1. Direct Key-Value Access (Quick & Simple)
Since PFObject stores data as key-value pairs, you can directly access fields using subscript syntax. Just remember to safely cast the value to the correct type—Parse fields might be missing or have unexpected types, so optional binding helps avoid crashes:
// Assume your PFObject instance is named scoreObject // Fetch the username field if let username = scoreObject["username"] as? String { print("Username: \(username)") // Will print "asd" for your example object } // Fetch the score field if let score = scoreObject["score"] as? Int { print("Score: \(score)") // Will print 888 for your example object }
2. Custom Parse Subclass (Type-Safe & Clean)
For larger projects, creating a custom subclass of PFObject makes your code more maintainable and reduces type-related errors. Here's how to set it up:
Step 1: Create the Score Subclass
import Parse class Score: PFObject, PFSubclassing { // Declare properties that match your Parse class fields @NSManaged var username: String? @NSManaged var score: Int? // Required: Return the exact name of your Parse class static func parseClassName() -> String { return "Score" } // Register the subclass (runs once when the class loads) override class func initialize() { guard self === Score.self else { return } registerSubclass() } }
Step 2: Register the Subclass
Add this line to your AppDelegate's application(_:didFinishLaunchingWithOptions:) method to let Parse recognize your custom subclass:
Score.registerSubclass()
Step 3: Access Fields as Properties
Now when you fetch objects from Parse, you can cast them to Score and access fields directly as properties:
// Assume fetchedObjects is the list you retrieved from Parse if let scoreObjects = fetchedObjects as? [Score] { for scoreObj in scoreObjects { if let username = scoreObj.username { print("Username: \(username)") } if let scoreValue = scoreObj.score { print("Score: \(scoreValue)") } } }
This approach eliminates repeated type casting and makes your code more readable for long-term projects.
内容的提问来源于stack exchange,提问作者MikeChenDeepL

