2012-03-19 39 views
0

對於我的UITableView,我使用一個數組作爲數據源。到目前爲止一切正常。但是,我有一個奇怪的問題,那就是當我使用搜索字段並輸入幾個字符,然後我再次刪除時,底層數組突然變空。下面的代碼片段,這可能是相關的,瞭解我的問題:數組突然變空

宣言在我的.h

@interface dictionaryViewController : UIViewController <UITableViewDelegate>{ 
... 
... 
    NSMutableArray *cardArray; 

} 

... 
@property (retain) NSMutableArray *cardArray; 
... 

使用在我的.m代碼:

@synthesize cardArray; 
... 

- (void)viewDidLoad { 
[super viewDidLoad]; 
self.cardArray = [[NSMutableArray alloc] initWithObjects:nil]; 
... 
} 

我用數據填充數組從我的SQL數據庫:

  [self.cardArray addObject:[NSString stringWithFormat:@"%@ - %@", aQuestion, anAnswer]]; 

和代碼內讀取陣列的內容,如在cellForRow甲基OD:

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
... 
thisCardIndex = [self.cardArray indexOfObject:cellValue]; 
... 
} 

最後我釋放它,像這樣(其實我曾與發佈命令,爲什麼我用了removeObjects,而不是其他一些問題):

[self.cardArray removeAllObjects]; 
    self.cardArray=nil; 

在我做日誌沒有看到錯誤。然而,調試器顯示代碼與SIGABRT崩潰,並且在設置斷點時我看到,原因是空的cardArray。

感謝您的支持。

+2

邏輯會錯somewhere..post烏爾整個的.m這裏文件.. – 2012-03-19 20:03:51

+1

在該方法是'[self.cardArray removeAllObjects]; self.cardArray =無;'?也許你應該發佈更多的方法。發佈命令有問題應該是紅旗。調用'removeAllObjects'不是必需的。將數組屬性設置爲nil將向所有對象發送一個版本。所以如果你不得不調用'removeAllObjects',你正在掩蓋一個不同的問題。 – SSteve 2012-03-19 20:32:05

回答

0

好的,終於找到了罪魁禍首,這是[myArray發佈](見下面的註釋行)。我不知道,爲什麼。這是一個本地數組,我在本地定義,也應該能夠立即釋放。有趣的部分是,只要搜索範圍縮小,此代碼就可以工作。當搜索字段再次爲空時,它只會崩潰。非常混亂,但也許有人有一個解釋?無論如何,終於得到它,並如預期的那樣。

- (void) searchTableView { 

NSString *searchText = searchBar.text; 
NSMutableArray *searchArray = [[NSMutableArray alloc] initWithObjects:nil]; 

for (NSDictionary *dictionary in self.listOfItems) { 
    NSArray *myArray = [dictionary objectForKey:@"Cards"]; 
    [searchArray addObjectsFromArray:myArray]; 

// [myArray release]; }

// Counter is needed to get the index of the primary key to dislpay the card in editViewController 
int aCounter=0; 
for (NSString *sTemp in searchArray) { 
    NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch]; 

    if (titleResultsRange.length > 0) { 
     [self.aCopyListOfItems addObject:sTemp]; 
     NSInteger myPrimaryKey; 
     myPrimaryKey = [[self.cardIDArray objectAtIndex:aCounter] integerValue]; 
     [self.aCopyOfCardIDArray addObject:[NSNumber numberWithUnsignedInteger: myPrimaryKey]]; 
    } 
} 

[searchArray removeAllObjects]; 
searchArray = nil; 
}