Reputation: 3350
I would like to create a simple method in one of my helper class that returns an NSString
, but I can't figure out the right way to return the value. I get this error inside the if statement.
Variable is not assignable (missing __block type specifier)
+ (NSString *) photoCount {
NSString *numberOfPhoto = [[NSString alloc] init];
PFQuery *photoQuery = [PFQuery queryWithClassName:@"PhotoContent"];
[photoQuery whereKey:@"usr" equalTo:[PFUser currentUser]];
[photoQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects) {
numberOfPhoto = [NSString stringWithFormat:@"%d", [objects count]];
}
}];
return numberOfPhoto;
}
What did I wrong? I've tried to return the string directly from the block, but it doesn't helped.
Upvotes: 0
Views: 75
Reputation: 438307
You are calling asynchronous method, so you cannot return the value immediately, but rather you want to adopt the asynchronous completion block pattern:
+ (void) photoCountWithCompletionHandler:(void (^)(NSInteger count, NSError *error))completionHandler {
NSParameterAssert(completionHandler);
PFQuery *photoQuery = [PFQuery queryWithClassName:@"PhotoContent"];
[photoQuery whereKey:@"usr" equalTo:[PFUser currentUser]];
[photoQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects) {
completionHandler([objects count], nil);
} else {
completionHandler(-1, error);
}
}];
}
And then when you call it, it would be something like:
[MyClass photoCountWithCompletionHandler:^(NSInteger count, NSError *error) {
if (error) {
// handle the error here
NSLog(@"photoCountWithCompletionHandler error: %@", error);
self.textLabel.text = @"?";
} else {
// use `count` here
self.textLabel.text = [NSString stringWithFormat:@"%ld", (long) count];
}
}];
// do not use `count` here, as the above block is called later, asynchronously
Upvotes: 2