在课堂上初学Singleton一次?

时间:2013-08-01 11:26:37

标签: iphone ios objective-c

我正在做以下事情以初始化我的singelton:

ChatDataController *box = [ChatDataController sharedInstance];

问题是我在不同的地方使用*框,例如在这些方法中:

- (void) viewDidAppear:(BOOL)animated
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

有没有办法只需要初始化一次?那么* box可以用在给定类中的任何方法中吗?

4 个答案:

答案 0 :(得分:2)

将此代码放入ChatDataController

+ (ChatDataController *)sharedInstance
{
    static ChatDataController *object = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object = [[ChatDataController alloc] init];
    });
    return object;
}

答案 1 :(得分:0)

  

有没有办法只需要初始化一次?

如果ChatDataController是单身,则只能初始化一次。

[ChatDataController sharedInstance]应始终返回相同的实例,并且在第一次调用时才返回alloc] init]

如果你在其中一条评论中提到过,你已经拥有了你的单身人士,那么只要你需要共享实例,就可以调用[ChatDataController sharedInstance]。无需将指针存储到属性中的对象。

答案 2 :(得分:-1)

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html

在“创建单例实例”

static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager
{
    if (sharedGizmoManager == nil) {
        sharedGizmoManager = [[super allocWithZone:NULL] init];
    }
    return sharedGizmoManager;
}

答案 3 :(得分:-1)

试试这个: - 在.pch文件中创建宏

首先导入类

#import"ChatDataController.h"

然后创建宏 (sharedInstance必须是类方法)

#define box ([ChatDataController sharedInstance]) 

之后你可以在所有类中使用这个对象