Tom Testicool
Tom Testicool

Reputation: 563

Parse iOS SDK: How to copy objectId while creating a PFObject

Scenario = I have a PFQueryTableViewController that will display messages that users send to each other. To create a relationship between the conversations, I saved a string to the object called "messageID". I want "messageID" to be an exact copy of the first message's "objectId" in order for the conversation to make chronological sense and I will 'orderByAscending' from the "createdAt" perimeter.

Question = How do I set (copy) the "objectId" from the first message?

The idea I am trying to do is this...

PFObject *message = [PFObject objectWithClassName:@"Message"];
[message setObject:[NSString stringWithFormat:@"%@", self.messageTextView.text] forKey:@"message"];
[message setObject:[PFUser currentUser][@"userID"] forKey:@"senderID"];
[message setObject:self.selectedFriendID forKey:@"receiverID"];

//RIGHT HERE
[message setObject:message.objectId forKey:@"messageID"];

[message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

}

The idea is this way all of the messages once queried in the PFQueryTableViewController will all belong together and in order because they all have the same "messageID".

This gives me an error 'Can't use nil for keys or values on PFObject. Use NSNull for values.'

If anyone could point me in the right direction so I can accomplish this I will love you.

Upvotes: 1

Views: 586

Answers (1)

Paulw11
Paulw11

Reputation: 114826

The error message tells you what is happening - you are trying to store a nil value in the messageID key, which isn't permitted.

The reason it is happening is the objectId is only assigned once the object is saved - a newly allocated object doesn't have a value yet.

So, you can either wait until the saveInBackgroundWithBlock has completed and retrieve the objectId then or you can use an alternative ID.

I would suggest you change your messageID column to a String and use a UUID. You can then create a new UUID before you save the first message in the conversation. You can use

NSString *messageID=[[NSUUID UUID] UUIDString];

Upvotes: 4

Related Questions