0

私は非ARCのプロジェクトに取り組んでいます。プロジェクトには、グローバル関数クラスのように使用されるシングルトンクラスがあります。

すべてが正常に動作します。次の問題を除いて:

  • ARCでクラスを追加しました
  • シングルトンクラスがARCベースのクラスからアクセスされると、初めて機能します
  • おそらく、シングルトンクラスをリリースしており、さらにシングルトンクラスを呼び出すと、「割り当て解除されたインスタンスにメッセージが送信されました」というメッセージが表示されてアプリがクラッシュします。

ARC対応クラスはシングルトンオブジェクトを解放するようなものだと想像できます。

どうすればこれを克服できますか?

編集:シングルトンクラス初期化子GlobalFunctions.m

#import "GlobalFunctions.h"
#import <CoreData/CoreData.h>
#import "UIImage+Tint.h"
#import "Reachability.h"
#if !TARGET_IPHONE_SIMULATOR
    #define Type @"Device"
#else
    #define Type @"Simulator"
#endif

@implementation GlobalFunctions

#pragma mark {Synthesize}
@synthesize firstLaunch=_firstLaunch;
@synthesize context = _context;

#pragma mark {Initializer}
static GlobalFunctions *sharedGlobalFunctions=nil;


- (UIColor *)UIColorFromRGB:(NSInteger)red:(NSInteger)green:(NSInteger) blue {
    CGFloat nRed=red/255.0; 
    CGFloat nBlue=green/255.0;
    CGFloat nGreen=blue/255.0;    
    return [[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1] autorelease];
}

#pragma mark {Class Intialization}
+(GlobalFunctions *)sharedGlobalFunctions{
    if(sharedGlobalFunctions==nil){
       // sharedGlobalFunctions=[[super allocWithZone:NULL] init];
        sharedGlobalFunctions=[[GlobalFunctions alloc] init]; //Stack Overflow recommendation, does'nt work
        // Custom initialization
        /* 
         Variable Initialization and checks
        */
        sharedGlobalFunctions.firstLaunch=@"YES";   
        id appDelegate=(id)[[UIApplication sharedApplication] delegate];        
        sharedGlobalFunctions.context=[appDelegate managedObjectContext];
    }
    return sharedGlobalFunctions;
}

-(id)copyWithZone:(NSZone *)zone{
    return self;
}
-(id)retain{
    return self;
}
-(NSUInteger) retainCount{
    return NSUIntegerMax;
}
-(void) dealloc{
    [super dealloc];
    [_context release];
}
@end

GlobalFunctions.h

#import <Foundation/Foundation.h>

@interface GlobalFunctions : NSObject<UIApplicationDelegate>{
    NSString *firstLaunch;

}

+(GlobalFunctions *)sharedGlobalFunctions; //Shared Object 
#pragma mark {Function Declarations}
-(UIColor *)UIColorFromRGB:(NSInteger)red:(NSInteger)green:(NSInteger) blue; // Convert color to RGB

#pragma mark {Database Objects}
@property (nonatomic,retain) NSManagedObjectContext *context;


@end

編集:

Anshuが提案したように、[[GlobalFunctionsalloc]init]を使用してみました。しかし、それでもアプリは「割り当て解除されたインスタンスに送信されました」というメッセージでクラッシュします

4

1 に答える 1

4

copyWithZone:まず、、、retainおよびretainCountメソッドを削除します。シングルトンでは役に立たない。

第二に、そのdealloc方法は間違っています。 [super dealloc] 常に最後のステートメントである必要があります

問題はあなたのシングルトンそのものです。retain何もしないようにオーバーライドしますが、オーバーライドしないでくださいrelease。ARCのクラスはretain、スコープの最初とrelease最後に呼び出す可能性があります。シングルトンreleaseはまだ実際には保持カウントをデクリメントするため、シングルトンの割り当てが解除されます。

上記のようにさまざまな方法を削除すると、正常に機能するはずです。

クラスはアプリのデリゲートではないため、GlobalFunctions実装として宣言しないでください。<UIApplicationDelegate>また、同じ管理対象オブジェクトコンテキストを取得する2つの手段があるのは奇妙です(ただし、致命的ではありません)。

于 2012-07-19T16:28:39.687 に答える