【问题标题】:Trouble understanding static class in iOS无法理解 iOS 中的静态类
【发布时间】:2013-09-10 16:41:26
【问题描述】:

我正在关注关于 iOS 编程的 Big Nerd Ranch 书籍。

有一个静态类的示例:

#import <Foundation/Foundation.h>

@interface BNRItemStore : NSObject

+ (BNRItemStore *) sharedStore;

@end

我在理解下面的 cmets 中带有问号的位时遇到了问题。 如果我尝试分配这个类,覆盖的方法会将我带到sharedStore,这反过来又将静态指针sharedStore 设置为nil。由于指针不存在,条件after会第一次命中。

这个想法是我第二次在同一个地方,它不会分配一个新的实例,而是获取现有的实例。但是对于static BNRItemStore *sharedStore = nil;,我将指针设置为 nil 并销毁它,不是吗?因此,每次我无意中创建一个新实例时,不是吗?

#import "BNRItemStore.h"

@implementation BNRItemStore

+ (BNRItemStore*) sharedStore
{
    static BNRItemStore *sharedStore = nil; // ???
    if (!sharedStore) {
        sharedStore = [[super allocWithZone:nil] init];
    }
    return sharedStore;
}

+(id)allocWithZone:(NSZone *)zone
{
    return [self sharedStore];
}

@end 

【问题讨论】:

  • 您拥有的是所谓的“单例”模式。最令人困惑的部分是,以static 开头的语句不是作为封闭方法的一部分执行的,而是仅在类加载时执行一次。
  • (我希望这本书实际上并没有将其称为“静态类”。)

标签: ios static


【解决方案1】:

但是对于static BNRItemStore *sharedStore = nil;,我将指针设置为nil 并销毁它,不是吗?

不,您没有将其设置为nilstatic 初始化程序中的表达式仅计算一次;第二次初始化没有效果。这看起来很混乱,但这是函数静态工具在 C 中的工作方式(以及在 Objective-C 中的扩展)。

试试这个例子:

int next() {
    static int current = 123;
    return current++;
}

int main(int argc, char *argv[]) {
    for (int i = 0 ; i != 10 ; i++) {
        NSLog(@"%d", next());
    }
    return 0;
}

这将产生一个从 123 开始的递增数字序列,即使代码使它看起来好像 current 每次执行该函数时都被分配了 123。

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多