【问题标题】:How to sucessfully call a BOOL method in an if statement? [duplicate]如何在 if 语句中成功调用 BOOL 方法? [复制]
【发布时间】:2014-07-16 03:30:36
【问题描述】:

更新:

我正在尝试从不同的类调用一个方法并将其放入 if 语句中,说“如果 uploadPhoto 方法为真,则显示成功以用于测试目的”这是我更新的代码:

PhotoScreen *script = [[PhotoScreen alloc] init];

if ([script uploadPhoto])
{
    NSLog(@"Sucess!");
}

它不再给我错误,但是当我从 uploadPhoto 方法中拍摄照片时,它没有记录“成功”,这是我的 uploadPhoto 方法:

- (BOOL)uploadPhoto
{
    //upload the image and the title to the web service
    [[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
      @"upload",@"command",
      UIImageJPEGRepresentation(photo.image,70),@"file",
      fldTitle.text, @"title",nil]
      onCompletion:^(NSDictionary *json)
      {
          //completion
         if (![json objectForKey:@"error"])
         {
             //success
             [[[UIAlertView alloc]initWithTitle:@"Success!"
                message:@"Your photo is uploaded"
                delegate:nil cancelButtonTitle:@"Yay!"
                otherButtonTitles: nil] show];
         }
         else
         {
             //error, check for expired session and if so - authorize the user
             NSString* errorMsg = [json objectForKey:@"error"];
             [UIAlertView error:errorMsg];

             if ([@"Authorization required" compare:errorMsg]==NSOrderedSame) 
             {
                 [self performSegueWithIdentifier:@"ShowLogin" sender:nil];
             }
         }
     }];
     return YES;
}

我做错了什么?

【问题讨论】:

  • 您的方法是否返回BOOL?另外你为什么要调用它两次?您也可以将[script uploadPhoto] 放在 if 语句中。
  • 我刚刚更改了返回 BOOL 的方法,它不再给我一个错误,但是当我尝试上传照片时它没有显示“成功”。有没有办法让它在哪里:一旦调用方法然后显示文本?
  • 只有当您的 uploadPhoto 方法返回 YES 时才会记录“成功”(顺便说一句 - 仅将 YESNO 用于 BOOL 值)。也许您应该在您的问题中发布您的 uploadPhoto 方法。
  • @Student 这是一个异步操作,我们不能立即将结果作为该方法的返回值返回。

标签: ios objective-c compiler-errors comparison return-value


【解决方案1】:

你的方法需要返回一个BOOL。在您的方法中,如果方法成功,您应该在某处有声明 return YES;,如果方法失败,则应该有 return NO;。您可以将代码修改为以下内容:

PhotoScreen *script = [[PhotoScreen alloc] init];

if ([script uploadPhoto])
{
    NSLog(@"Sucess!");
}

除了比较之外,重复的方法调用是不必要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2015-01-26
    • 2015-12-12
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多