Appending PFObject to Array - EXC_BAD_ACCESS

360 Views Asked by At

I am currently using Swift and Parse and have run into an issue which I haven't been able resolve for the past several hours.

On a button click, I am attempting to add an Employee object to an Event object's eventAttendee's array.

@IBAction func joinEvent(sender: AnyObject) {
    var employee = Employee.currentUser()
    employee.events.append(event)
    employee.saveInBackgroundWithBlock(nil)

    event.eventAttendees.append(employee)
    event.saveInBackgroundWithBlock(nil)
}

The event is added to the employee events, but the employee is not added to the event attendees list. The function throws a EXC_BAD_ACCESS (code=1, address=0x0) on the append(employee) line, with no other error message.

My event class looks like this:

class VolunteerEvent : PFObject, PFSubclassing {

@NSManaged var eventName: String
@NSManaged var dateOfEvent: NSDate
@NSManaged var eventDescription: String
@NSManaged var eventURL: String?
@NSManaged var eventImage: PFFile

@NSManaged var contactEmail: String
@NSManaged var contactPhone: NSNumber

@NSManaged var eventOrganizer: Employee
@NSManaged var eventAttendees: [Employee]

class func parseClassName() -> String {
    return "VolunteerEvent"
}
}

My Employee class extends PFUser, although when I print out the description of my employee I get that it is a PFUser. I can't tell if this is the issue. When I print out the event, it looks like I expect it to look. I also tried switching the eventAttendees to be an array of PFUser's instead of Employee's, but that didn't work either.

Any help would be much appreciated. Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER

I subclass my PFObjects this way,

class Person : PFObject, PFSubclassing {

    var firstName: String {
        get {
            return objectForKey("firstName") as? String ?? ""
        }
        set {
            setObject(newValue, forKey: "firstName")
        }
     }
}

This way if there is no string in the parse database, I don't get nil, i get an empty string.

You can do this with your array, in fact all your object properties.

If nothing is returned, then you will get an empty array of Employee, rather than a nil object - which will cause your crash when you try an append to it.

0
On

You need to initialize your array before adding to it. Try var eventAttendees: [Employee] = []