我澄清了我之前的问题。 How can I retrieve multiple data simultaneously? (Parse DB, iOS)
你好,我是Parse和数据库的新手,我在这里苦苦挣扎。
在视图上,有4个按钮和一个标签。
所以基本上我想做的是首先检索列@"A"
的对象(同时在标签上显示数据),然后检索同一行的属性。
当我按下任何其他按钮时,他们应该显示查询属性,该属性与@"A"
但是目前这个代码每次按下按钮都会运行一个查询,所以每四个都是乱七八糟地向视图发送不同的随机数据。
此外,日志执行错误:Warning: A long-running Parse operation is being executed on the main thread. Break on warnParseOperationOnMainThread() to debug.
如果有人可以帮我解决这个问题,我会很高兴。
PFQuery *query = [PFQuery queryWithClassName:@"DataClass"];
//get a data(object) randomly
int count = [query countObjects];
int randomCount = arc4random() % count;
query.skip = randomCount;
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
//retrieving data... but asynchronously!
NSString *getTheStr1 = object[@"A"];
NSString *getTheStr2 = object[@"B"];
NSString *getTheStr3 = object[@"C"];
NSString *getTheStr4 = object[@"D"];
//when I press a button, each shows a different text on the label.
UIButton *button = (UIButton *)sender;
switch ([button tag]) {
case 1:
Label.text = [NSString stringWithFormat:@"%@", getTheStr1];
break;
case 2:
Label.text = [NSString stringWithFormat:@"%@", getTheStr2];
break;
case 3:
Label.text = [NSString stringWithFormat:@"%@", getTheStr3];
break;
case 4:
Label.text = [NSString stringWithFormat:@"%@", getTheStr4];
}
}
}];
答案 0 :(得分:0)
你得到的是因为行[query countOfObjects];
对象计数是一个同步函数,它转到解析服务器以获取信息。即这是主线程上的一个长期运行过程。
你应该使用这个功能......
[query countObjectsInBackgroundWithBlock...
然后在完成块中你可以用计数信息做点什么。
即。生成一个随机数,然后运行查找第一个函数。
编辑以显示如何完成此操作
- (PFQuery *)query
{
PFQuery *query = [PFQuery queryWithClassName:@"DataClass"];
return query;
}
// putting the button in here for the tag.
// it should not be here though.
// using tags is never the way to go.
- (void)getRandomSkipForQuery:(UIButton *)button
{
PFQuery query = [self query];
[query countObjectsInBackgroundWithBlock:^(NSInteger count, NSError *error) {
// check for errors...
// don't use arc4random % something
NSInteger randomCount = arc4random_uniform(count);
[self getObjectWithSkip:randomCount button:button];
}];
}
- (void)getObjectWithSkip:(NSInteger)skip button:(UIButton *)button
{
PFQuery *query = [self query];
query.skip = skip;
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
//ugh this is really bad design
//when I press a button, each shows a different text on the label.
switch ([button tag]) {
case 1:
//variables begin with a lowercase letter
label.text = [NSString stringWithFormat:@"%@", object[@"A"]];
break;
case 2:
label.text = [NSString stringWithFormat:@"%@", object[@"B"]];
break;
case 3:
label.text = [NSString stringWithFormat:@"%@", object[@"C"]];
break;
case 4:
label.text = [NSString stringWithFormat:@"%@", object[@"D"]];
}
}
}];
}
我真的不喜欢使用标签来设计显示内容的设计。这很糟糕。
你最好做一些事情,比如根据按下哪个按钮来设置枚举属性。无论如何都是这样的。