2010-09-20 103 views
0

我有這段代碼,我做錯了什麼?重新裝載表/數組與功能?

我有一個函數,我稱之爲將一些字符串放入數組中。然後在某些時候我想在用戶編輯字符串之後重新加載它。這是函數:

NSMutableArray *lessonsFunc(id a, id b, id c, id d, id e, id f){ 
    monData *mon = [monData sharedData]; 
    return [NSMutableArray arrayWithObjects:@"Before School", 
              [NSString stringWithFormat:@"%@", a], 
              [NSString stringWithFormat:@"%@", b], 
              @"Break", 
              [NSString stringWithFormat:@"%@", c], 
              [NSString stringWithFormat:@"%@", d], 
              @"Lunch", 
              [NSString stringWithFormat:@"%@", e], 
              [NSString stringWithFormat:@"%@", f], 
              @"After School", nil]; 
} 

我這樣稱呼它:

monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S); 

然後,我要重新加載/刷新它,當我按下按鈕:

-(IBAction)refreshLessons{ 
    monData *mon = [monData sharedData]; 
    //[monArrayA removeAllObjects]; 
    //[monArrayA release]; 
    //monArrayA = [[NSMutableArray alloc] init]; 
    monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S); 
    //[monTable reloadData]; 
} 

它崩潰幾乎總是當我按下那個按鈕。非常感謝任何幫助,謝謝!

回答

1

可能的問題是lessonsFunc返回的自動釋放數組可能會在當前作用域之外變得無效(這裏是refreshLessons函數的外部)。儘量保留它以保持它的有效性,只要你需要。要做到這一點,我建議要聲明一個屬性爲您的陣列 - 編譯器將自動爲您生成setter和getter方法,將處理大多數內存管理爲您提供:

// header 

@property (nonatomic, retain) NSMutableArray * monArrayA; 

//Implementation 
@synthesize monArrayA; 
... 
-(IBAction)refreshLessons{ 
    monData *mon = [monData sharedData]; 

    self.monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S); 
} 
... 
- (void)dealloc{ 
    // Don't forget to release monArrayA in dealloc method 
    [monArrayA release]; 
    ... 
    [super dealloc]; 
} 
+0

啊我想這可能是事做與此,但沒有鎖住(典型的我!)謝謝!!!!! – 2010-09-20 14:22:42

+0

雖然有一個小問題,是否有一個原因,我必須說self.monArrayA而不是monArrayA? – 2010-09-20 14:26:18

+1

self.monArrayA相當於調用[self setMonArrayA]方法(如果使用@synthesize,則自動生成),並且monArrayA被保留在其中。你可以寫monArrayA = [lessonFunc()retain],但是你需要手動釋放以前的monArrayA值。使用屬性使生活變得更容易 – Vladimir 2010-09-20 14:46:12