2

プロジェクトにARCを使用しています

私はこのような1つのクラスを持っています:

@implementation MyObject

+ (instancetype)shareInstance {
    static id _shareInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _shareInstance = [[self alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(freeInstance)
                                                     name:kLC_Notification_FreeAllInstance object:nil];
    });
    return _shareInstance;
}
+ (void)freeInstance {
    /*I want to release object "_shareInstance" but how??? */
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

しかし、インスタンス オブジェクトを解放できないため、次のように変更する必要があります。

(コード行 static id _shareInstance = nil;を外に移動+shareInstance

@implementation MyObject
static id _shareInstance = nil;
+ (instancetype)shareInstance {
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _shareInstance = [[self alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(freeInstance)
                                                     name:kLC_Notification_FreeAllInstance object:nil];
    });
    return _shareInstance;
}
+ (void)freeInstance {
    _shareInstance = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

name:kLC_Notification_FreeAllInstance で通知をプッシュすると、すべてのインスタンス オブジェクトが解放されます (すべての dealloc メソッドが両方とも呼び出されます)。大丈夫です

しかし、もう一度呼び出すと....

次の呼び出しですべてのインスタンスが初期化されるわけではありません。その後、すべてのインスタンスオブジェクトは nil になります

のブロックに多くのブレークポイントを作成しましたが、dispatch_onceブレークポイントは呼び出されません。


だから私の質問は:

  1. メソッド内での書き込みstatic id object;とメソッド外への書き込みは違いますか?

  2. すべてのインスタンス オブジェクトを解放して、再度呼び出すことができるようにするにはどうすればよいですか? (ARC を使用したいのですが、ARC なしで実行できます)

4

2 に答える 2

3

oncePredicateリリース時は0にすればいいと思う_shareInstance

@implementation MyObject
static id _shareInstance = nil;
static dispatch_once_t oncePredicate;
+ (instancetype)shareInstance {
    dispatch_once(&oncePredicate, ^{
        _shareInstance = [[self alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(freeInstance)
                                                     name:kLC_Notification_FreeAllInstance object:nil];
    });
    return _shareInstance;
}
+ (void)freeInstance {
    _shareInstance = nil;
    oncePredicate = 0;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

わたしにはできる!

于 2014-03-11T11:17:54.870 に答える