【问题标题】:iOS Parse Block results stored in a UILabeliOS Parse Block 结果存储在 UILabel 中
【发布时间】:2013-10-03 03:58:41
【问题描述】:

我正在使用 Parse iOS SDK,我想存储我的 findObjectsInBackgroundWithBlock: query in aUILabel. TheUILabelis created inside of theviewForHeaderInSection`:我的表格视图的方法。

如果我在块内创建UILabel,我可以成功存储我需要的值并在我的视图上显示标签。当查询在 Parse 中运行时,它会在查询使用本地缓存之前尝试连接到服务器 3 次。如果任何尝试失败或与服务器的连接速度很慢,我的UILabel 会闪烁。我不希望这样,所以我的想法是在块完成后以某种方式访问​​我的查询结果并将其存储为UILabel

有人可以告诉我如何在块外访问我的查询结果并将结果存储在UILabel 中吗?

下面的示例是我当前如何在视图上创建UILabel 并将我的块结果显示为UILabel。感谢您的帮助!

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
        {
                UIView *myHeader = [[UIView alloc] initWithFrame:CGRectMake(0,60,320,20)];
                myHeader.backgroundColor = [UIColor grayColor];

                PFQuery *query = [PFQuery queryWithClassName:@"ClassName"];
                query.cachePolicy = kPFCachePolicyNetworkElseCache;
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

                if (!error) 
                {
                    NSNumber *sum = [objects valueForKeyPath:@"@sum.sumResults"];
                    UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(15,0,120,20)] ;
                    myLabel1.font = [UIFont boldSystemFontOfSize:14.0];
                    myLabel1.text = [NSString stringWithFormat:@"Sum results: %.1f", [sum floatValue]];
                    [myHeader addSubview:myLabel1];

                } 
                else 
                {
                     NSLog(@"Error: %@ %@", error, [error userInfo]);
                }

        }];

        return myHeader;
    }

【问题讨论】:

    标签: ios objective-c parsing uitableview block


    【解决方案1】:

    问题的很大一部分是您在“findObjectsInBackgroundWithBlock”结果(完成)块中创建标签。因此,您的应用程序中除该代码块之外的任何其他地方都不容易使用它。

    我建议您将 UILabel 作为 IBOutlet(即,将其放入情节提要或 xib 文件中,并将其连接到视图控制器中的插座)。

    然后,当您获得想要显示的结果时,post a notification to yourself (or any observers) that it's time to update(我推荐 postNotificationName:object:userInfo:,其中 userInfo 字典包含您要添加到该标签的任何信息)。

    【讨论】:

      【解决方案2】:

      您正在一个块中创建标签,使其无法用于您的其余代码。 为了从块外部访问标签,请在您的 .m 文件中创建一个属性:

      @interface YourViewController()
      //here comes your label
      @property (strong, nonatomic) UILabel *myLabel1;
      @end
      

      然后在你的@implementation 之后合成它:

      @implementation YourViewController
      @synthesize myLabel1;
      

      现在,而不是调用

      UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(15,0,120,20)];
      

      只需调用

      myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(15,0,120,20)];
      

      然后您可以从代码中的任何位置访问您的标签(但请确保您在尝试访问它时已经启动它!在您的情况下,当您坚持在 viewForHeaderInSection 方法中启动它时,请确保您访问它仅在调用此方法并且标签已有效启动后。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-06
        • 1970-01-01
        • 1970-01-01
        • 2015-07-27
        相关资源
        最近更新 更多