2012-11-30 41 views
0

使用字符串崩潰的應用程序。
temp是普通字符串,strStartDate也是Date的字符串。 .h文件中打印時出現應用程序崩潰NSString

NSString *temp; 
NSString *strStartDate 
int status; 

.m文件

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    status = 1; 
    strStartDate=[[NSString alloc]init]; 
    [self stateChanged]; 
} 
-(void)stateChanged 
{ 
    switch(status) 
    { 
    case 0: 
     NSLog(@"%@",temp); 
     NSLog(@"Start Date : %@",strStartDate); 
     break; 

    case 1: 
     temp=[[NSString alloc]initWithString:@"Temp is here"]; 
     chargeStartDate=[[NSDate date] retain]; 
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
     [dateFormat setDateFormat:@"dd/MM/YYYY"]; 
     strStartDate = [dateFormat stringFromDate:chargeStartDate]; 
     NSLog(@"string of start date : %@",strStartDate); 
     [timeFormat release]; 
     [dateFormat release]; 
     break; 
    } 
} 

temp是普通字符串,strStartDate也從日期字符串。 字符串tempstrStartDate都分配相同的地方,既是類變量,又在case 0中打印相同的地方temp是打印,而strStarDate崩潰。爲什麼?

我知道這很簡單,但我無法理解。請幫幫我。

+0

這只是一個預感,但你的意思是'dd/MM/yyyy'而不是'dd/MM/YYYY'? – John

+0

在你使用ARC的應用程序中? –

+0

在你上面指定狀態= 1,那麼在情況0下如何控制? –

回答

1

您需要在使用stringFromDate初始化之後對strStartDate執行retain。該調用的結果將被自動釋放,因此您需要一個保留來停止釋放該對象。

+0

完美。非常感謝。但是,你能解釋一下爲什麼我們不需要保留臨時字符串。它工作正常,沒有保留。 –

+0

@combinatorial但沒有自動釋放池。 –

+0

系統總是提供一個自動釋放池 – combinatorial

0

它的發生,因爲在strStartDate變量沒有值存儲,它是nil(NULL)所以當你想在那個時候它沒有得到字符串值,因此應用程序崩潰..

%@打印出來嘗試先分配strStartDate = @"";然後打印它,它會工作..

+0

strStartDate = [dateFormat stringFromDate:chargeStartDate]; ,op是賦值給strStartDate。 –

+0

@ParagBafna閱讀問題,這裏的應用程序墜毀在案件0隊友.. :) –

+1

它應該打印(空)。 –

相關問題