【问题标题】:Can't understand the code example in xcode看不懂xcode中的代码示例
【发布时间】:2016-11-01 12:08:27
【问题描述】:

我正在尝试将代码从 swift xcode 转换为 c# (xamarin)。我看不懂下面的代码:

#pragma mark - Implement DTBackgroundView Class

@interface DTBackgroundView : UIView
{
    UIWindow *_previousKeyWindow;
    UIWindow *_alertWindow;
    NSMutableArray *_alertViews;
}

+ (Instancetype)currentBackground;

static DTBackgroundView *singletion = nil;

@implementation DTBackgroundView

+ (Instancetype)currentBackground
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singletion = [DTBackgroundView new];
    });

    return singletion;
}

我的问题是:

  1. currentBackground是谁?

  2. 以下代码中的backgroundView是什么:

DTBackgroundView *backgroundView = [DTBackgroundView currentBackground];

【问题讨论】:

  • 您需要查阅designPatterns 书籍来了解singleton 类。而且您发布的代码不在 Swift 它的 Objective-C 中。

标签: c# ios objective-c xcode xamarin


【解决方案1】:

正如 Adeel 在他的评论中所说,那是 Objective-C 代码,而不是 Swift。您已经发布了 DTBackgroundView 类的实现。

currentBackground 方法是一个类方法(或在 C++ 中调用的“静态方法”),用于请求类的单例实例。如果已经创建了单例,则该方法将其返回。如果没有,它会创建单例并返回它。

您应该阅读单例设计模式并使用 C# 中创建单例的任何约定。

我不会太担心尝试对该代码进行逐行转换 - 它使用特定于 Cocoa(iOS 和 Mac OS)的GCD(Grand Central Dispatch)。只需找到用于创建和返回单例的 C# 约定并使用它。

【讨论】:

  • 你能扩展首字母缩写词 GCD 吗?读者(比如我自己)可能不熟悉它。
  • Google 是您的朋友。 GCD 代表 Grand Central Dispatch。上面有一篇 wiki 文章:en.wikipedia.org/wiki/Grand_Central_Dispatch
  • 同意,Google 是我的朋友(很快就知道它是什么),但我认为将其嵌套到答案中会很有用 :)
猜你喜欢
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 2013-11-01
  • 2021-08-22
  • 2017-10-13
  • 2023-03-28
  • 2012-05-08
  • 1970-01-01
相关资源
最近更新 更多