2011-04-07 74 views
1

我已經建立了一個單獨的對象,以我的應用程序無效CFArrayRef問題

@interface MyCommon : NSObject { 

    NSArray *quizz; 
    int iCurrentQuestion; 

}; 

+ (MyCommon *)singleton; 

@property (retain) NSArray *quizz; 
@property (assign) int iCurrentQuestion; 

@end 

MyCommon.m 

#import "MyCommon.h" 


// MyCommon.m: 
@implementation MyCommon 

static MyCommon * MyCommon_Singleton = nil; 


@synthesize iCurrentQuestion; 

+ (MyCommon *)singleton 
{ 
    if (nil == MyCommon_Singleton) 
    { 
     MyCommon_Singleton = [[MyCommon alloc] init]; 
     NSLog(@"allocating MyCommon_Singleton at %@",MyCommon_Singleton); 
    } 
    else { 

     NSLog(@"accessing singleton : %@", MyCommon_Singleton); 
    } 

    return MyCommon_Singleton; 
} 


- (NSArray*) getQuizz{ 

    return quizz; 
} 

- (void) setQuizz:(NSArray *)array { 

    quizz = [NSArray arrayWithArray:array]; 

    NSLog(@"setQuizz : %@",quizz);  
} 

沒有爲寫QUIZZ對象(setQuizz)沒有問題,管理一些數據,但是當我嘗試訪問它閱讀,我得到一個崩潰:在QUIZZ看起來無效,Xcode中通知我無效CFArrayRef

我不知道什麼是錯我的代碼。

回答

2

您提供quizz一個自定義的制定者,但它不與物業是如何聲明的規定。

你不保留quizz當你設置一個新值。它很可能會在剛剛發佈時導致崩潰,當您訪問它時。

你應該寫

+0

做你忘了在上面的代碼的東西嗎?我的日誌 – 2011-04-07 15:30:51

+0

@ N-AccessDev遺憾的錯字得到setQuizz(空)。我寫'TMP = [陣列保留]的''代替QUIZZ = [陣列保留]' – Jilouc 2011-04-07 15:35:08

+0

它工作感謝;) – 2011-04-07 15:51:25

0

這是比它需要的方式更多的代碼。首先,如果你要提供你自己的方法,你應該在@property聲明中聲明你沒有的聲明。此外你沒有妥善保留你的變量。此外,你應該使用dispatch_once()的線程安全&快速的方式,以保證只創建一次單。

@interface MyCommon : NSObject {} 

@property(nonatomic, retain) NSArray *quiz; 
@property (assign) int iCurrentQuestion; 

+ (MyCommon *)singleton; 

@end 

@implementation MyCommon 

@synthesize quiz; 
@synthesize iCurrentQuestion; 

-(id)init { 
    self = [super init]; 
    if(self) { 
     quiz = [[NSMutableArray alloc init]; 
     iCurrentQuestion = 0; 
    } 
    return self; 
} 

+ (MyCommon *)singleton { 
    static MyCommon *singleton = nil; 
    static dispatch_once_t pred; 

    dispatch_once(&pred, ^{ 
     singleton = [[MyCommon alloc] init]; 
    }); 
    return singleton; 
} 

@end 

那麼你只是做

[MyCommon singleton].quiz = //some array