ios - 使用 if 语句的结果作为变量

标签 ios objective-c uiimageview

我想知道是否有使用 的方法方法的返回值 ,即 由 if 语句检查 ,作为 变量 如果不为零 .

我希望下面的代码示例有助于解释我所追求的。

假设我有一个返回 UIImageView 的方法, -(UIImageView *)imageViewExistsForID:(NSString *)viewID .在其他地方的方法中,我想检查该 imageView 是否返回一个值,并且由于它是有条件的,因此使用 if 语句,如下所示:

if ([self imageViewExistsForID:<VIEWID>]) {

// Use the returned imageView here

}
else {

// 'nil' was returned, so no need to use the result

}

通常,我会在 if 语句之前声明一个占位符变量,例如:
UIImageView *returnedImageView = [self imageViewExistsForID:<VIEWID>];

if (returnedImageView) {
...etc

我只是想知道是否有一种方法可以在 if 语句首次检查时从方法中传递结果,而不必先将结果存储在变量中,这更类似于:
if ([self imageViewExistsForID:<VIEWID>]) {

    UIImageView *imageView = if-statement-result 
    // ??? (i.e. don't call the method again [self imageViewExistsForID:<VIEWID>])

}

免责声明:我纯粹是从一个智力好奇的角度提出这个问题,因为这显然不是一个阻止我在代码中实现任何东西的“问题”。我总是热衷于了解更多关于 Objective-C 的知识,因为我认为自己对它的阅读还不够。感谢任何可以让我知道这一点的人 - 如果我无法理解,请道歉!

最佳答案

不,没有办法使用 if 条件的结果。您必须声明一个占位符变量。

if 中初始化占位符是可能的,在某些情况下甚至是允许的。陈述

UIImageView *returnedImageView;

if ((returnedImageView = [self imageViewExistsForID:<VIEWID>])) {

注意额外的括号;使用 =而不是 ==是一个常见的错误,因此编译器可能会发出警告而不用括号括起来。

关于ios - 使用 if 语句的结果作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598386/

相关文章:

ios - 让 UIView drawRect 出现在后台线程中

ios - Apple 允许的推送通知的最大允许数量

ios - 从 iOS 应用程序到 Google 表单的 HTTP POST

iPhone - MFMailComposeViewController 委托(delegate)不兼容的类型

ios - Swift:将图像设置为自定义单元格ImageView

ios - 使用 Parse 时关闭 iOS 中的登录屏幕

ios - 为什么 xctool 在 NSRegularExpression 匹配时崩溃?

ios - 在 iOS7 上看不到动态 subview (在 iOS6 上工作)

ios - Collection View 更新问题 - Swift

ios - 如何检测快速点击了哪个图像