I have a code snippet that will update information in the Parse database. I set up an action so that when the information is saved, it gets updated in the background. The function is being executed, but it's not saving anything on the database. its going through the function, but no changes are being saved. The changed values are inside a text field and a switch.
- (IBAction)save:(id)sender {
NSLog(#"classnameinsave %#", self.productTitleField.text);
PFQuery *query = [PFQuery queryWithClassName:self.className];
[query getObjectInBackgroundWithId:self.productId block:^(PFObject *object, NSError *error) {
NSLog(#"inside getObjectsInBackgroundWithId function");
NSLog(#"priceinsave %#", object[#"price"]);
object[#"title"] = self.productTitleField.text;
object[#"price"] = self.priceField;
object[#"quantity"] = self.quantityField;
object[#"show"] = self.show;
[object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(succeeded){
NSLog(#"Succeeded in Saving");
}else if(error){
NSLog(#"Error with saving changes %#", error);
}
}];
}];
}
Most likely this happened because the PFObject you're looking for doesn't even exist! You forgot to add the if statement for verifying if the object exists. Also, I understand you want to make it as dynamic as possible by having the class name based on a UILabel, but please don't do this, this doesn't make sense at all. Replace your code with this:
PFQuery *query = [PFQuery queryWithClassName:#"ClassName"];
[query getObjectInBackgroundWithId:self.productId block:^(PFObject *object, NSError *error) {
if(object){
//Do everything here :)
}else{
//Display an UIAlertView to the user?
NSLog(error);
}
}];
Note: You should add the if statement, however it's not necessary.
Best regards,
Related
I need to upload some data to server. Just before doing so, I fetch an entity that this data should be bounded to(simple relationship). If there is no such entity, I want to create it then and continue uploading process. The problem, though, is that if there are too many requests, all requests will end up faster than creation of the entity, thus many entities will be created. The solution is to dispatch the block of code synchronously, but on a different thread. How do I do this?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
PFQuery *query = [PFQuery queryWithClassName:#"FileOwner"];
[query whereKey:#"identifier" equalTo:#"ABCDEFG"];
PFObject *fileOwner = [query getFirstObject];
if(fileOwner){
[self continueUploadingData:data completionHandler:completionBlock];
}
else{
PFObject *newFileOwner = [PFObject objectWithClassName:#"FileOwner"];
newPhotoOwner[#"identifier"] = #"ABCDEFG";
[newPhotoOwner saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(succeeded)[self continueUploadingData:data completionHandler:completionBlock];
}];
}
});
This works, but obviously blocks the main thread. I can't use detachSelector: toTarget: withObject: because I have more than one argument.
The general purpose advice that will help here is to build the atomic functions with methods that take completion blocks (like parse's, maybe like your continueUploading method).
In this case, we need a function that will look for an object, return it if it's found, or create and return it if it's not found, all asynch...
- (void)findOrCreateFileOwnerWithIdentifier:(NSString *)identifier completion:(void (^)(PFObject *, NSError *))completion {
PFQuery *query = [PFQuery queryWithClassName:#"FileOwner"];
[query whereKey:#"identifier" equalTo:identifier];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (object) {
return completion(object, nil);
} else {
PFObject *newFileOwner = [PFObject objectWithClassName:#"FileOwner"];
newFileOwner[#"identifier"] = identifier;
[newFileOwner saveInBackgroundWithBlock:completion];
}
}];
}
Now you can say...
[self findOrCreateFileOwnerWithIdentifier:#"ABCDEFG" completion:^(PFObject *fileOwner, NSError *error) {
if (!error) {
[self continueUploadingData:data completionHandler:completionBlock];
} else {
// handle error... probably pass it to completionBlock
// not shown because the OP code doesn't show how the block is declared
}
}];
Newbie question... I am trying to set a variable self.projectName in a code block but when I call it outside the code block, the value is not retained. After reading more about code blocks, it seems like there are some rules on when values become available but I'm still not clear why I can't set the value for use later...any help would be much appreciated!
PFQuery *query = [PFQuery queryWithClassName:#"ScheduledProjects"];
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) {
if (!error) {
PFObject *project = [projects objectAtIndex:indexPath.row];
self.projectName = project[#"name"];
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
NSLog (#"project name = %#",self.projectName);
The block is meant to be called asynchronously, which means that after you defined it you don't know exactly when it will finish executing.
To use the variable try creating a callback function and calling it at the end of the block. There you will know for sure that it has been executed.
Example:
-(void)yourMethod{
PFQuery *query = [PFQuery queryWithClassName:#"ScheduledProjects"];
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) {
if (!error) {
PFObject *project = [projects objectAtIndex:indexPath.row];
self.projectName = project[#"name"];
[self callback];//You call the method when your block is finished
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
//Here you could call a different callback for error handling (or passing a success param)
}
}];
}
-(void) callback{
//Here you know the code has been executed
NSLog (#"project name = %#",self.projectName);
}
I am having trouble saving a PFRelation I have this code:
//set up the query
PFQuery *query = [PFQuery queryWithClassName:#"messageBank"];
[query whereKey:#"username" equalTo:name];
__weak User *weakSelf = self;
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if(error) {
NSLog(#"No such user");
handler(NO, error,NO,NO);
}
else{
[weakSelf.friendsRelation addObject:object];
[weakSelf.friends addObject:object];
//save in the background
[weakSelf.messageBank saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error) {
NSLog(#"Save error");
}
else {
NSLog(#"no error");
}
}];
handler(YES,nil,NO,NO); //no errors
//so the friend is added to the friends array, all we need to do is reload the table data don't need to init the array again, the relation is also added to the relation item so don't need to init that again
}
}];//end block
My code finds the messageBank object fine but it won't save it to the PFRelation friends. It doesn't even attempt to call [weakSelf.messageBank saveInBackgroundWithBlock.... weakSelf.messageBank is the local PFObject and weakSelf.friends is it's PFRelation. Anyone have any ideas what could be going wrong here? If I have a PFRelation in class A is it okay to have pointers in that relation to other objects in class A? Does it need to be in a different class? Any help would be much appreciated!!!
Here's a cleaned up version of the code that fetches an object and adds to its relation, and saves it...
PFQuery *query = [PFQuery queryWithClassName:#"messageBank"]; // by convention class names should be capital MessageBank, but using yours
[query whereKey:#"username" equalTo:name]; // better form is self.name assuming it is an attribute of self
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
// see note below about weakSelf
// assume self is a PFObject subclass with two relations
// (and generated setters) called friendsRelation and friends
[self.friendsRelation addObject:object];
[self.friends addObject:object];
// notice we save self here. that's who changed in the two preceding lines
[self saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(!error) {
// success
} else {
// handle error
}
}];
} else {
// handle error
}
}];
Please notice that there's no need to declare a __weak copy of the self pointer (though, there's no harm in it). That idiom is used to avoid a retain cycle between self and the block's owner. You need it only when self is the blocks owner (directly or indirectly). This isn't the case with parse's completion blocks.
I have a class on Parse.com called "Hospital", which has a few rows on it. I want to query all the rows in this object, and then selectively delete some of them.
I figure I need to cycle through the object, gathering the objectIDs, and then look at the row associated with each ID to figure out which ones should be deleted. I can't find how to do this anywhere. I've tried this:
PFQuery *query = [PFQuery queryWithClassName:#"Hospital"];
But this returns an object with 0 objects inside it, when there is definitely a row in the Parse.com database.
Once I get this part working, and get objectIDs, it seems I can delete a row with the following:
PFObject *testObject = [PFObject objectWithoutDataWithClassName:#"Hospital" objectId:#"NMZ8gLj3RE"];
[testObject deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded){
NSLog(#"BOOOOOM"); // this is my function to refresh the data
} else {
NSLog(#"DELETE ERRIR");
}
}];
PFQuery *query = [PFQuery queryWithClassName:#"Hospital"];
[query findObjectsInBackgroundWithBlock:^(NSArray *hospitals, NSError *error) {
if (!error)
{
for (PFObject *hospital in hospitals)
{
if ([hospital.objectId isEqualToString:#"NMZ8gLj3RE"])
{
[hospital deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded){
NSLog(#"BOOOOOM"); // this is my function to refresh the data
} else {
NSLog(#"DELETE ERRIR");
}
}];
}
}
}
else
{
NSLog(#"%#",error);
}
}];
I use this code to update my data on data browser on parse.
PFQuery *query = [PFQuery queryWithClassName:#"UserInformation"];
[query getObjectInBackgroundWithId:#"dIwnk9tbr0" block:^(PFObject *gameScore, NSError *error)
{
gameScore[#"email_address"] = #"testkolang#y.com";
[gameScore saveInBackground];
}];
But I have this kind of error. And the data on parse is not changed.
2014-03-12 18:08:06.036 AndroidiOsPushTest[3725:1803] Error: object not found for update (Code: 101, Version: 1.2.18)
PFQuery *query = [PFUser query];
[query getObjectInBackgroundWithId:objectID block:^(PFObject *UserInfo, NSError *error) {
if (!error) {
[UserInfo setObject:self.userName.text forKey:#"username"];
[UserInfo setObject:#"US" forKey:#"country"];
[UserInfo saveInBackground];
}
else {
// Did not find any UserStats for the current user
NSLog(#"Error: %#", error);
}
}];
Your issue looks like the one in : I can not update a record in Parse; Error: "object not found for update (Code: 101, Version: 1.2.16)"
Error code 101 in Parse means :
101: Object doesn't exist, or has an incorrect password.
First, you should check if your object exists and if the error is not null.
Then, if these steps are successful, you should check for the ACL of the object : if you don't have permissions to edit it, you will be unable to save it and get the error 101.
It relate to ACL, please check your dashboard for the data column "ACL"
The write should lock on specific user ID. you need change it from your dashboard to update its permission to
{"*":{"write":true,"read":true}}
You can check more detail on my reply in this
From Parse.com (Hector Ramos)
PFQuery *query = [PFQuery queryWithClassName:#"UserStats"];
[query whereKey:#"user" equalTo:[PFUser currentUser]];
[query getFirstObjectInBackgroundWithBlock:^(PFObject * userStats, NSError *error) {
if (!error) {
// Found UserStats
[userStats setObject:newScore forKey:#"latestScore"];
// Save
[userStats saveInBackground];
} else {
// Did not find any UserStats for the current user
NSLog(#"Error: %#", error);
}
}];