2009-10-12 72 views
0

這是一個後續FORR iPhone SDK: loading UITableView from SQLiteiPhone SDK:從SQLite的加載UITableView中 - 創建陣列從SQLite的

我打算使用下面的代碼來SQL數據加載到陣列。陣列中的每個元素將是代表每個數據庫條目的類:

@interface行:NSObject {PKI; NSString * desc;

}

@property int PK; @property(nonatomic,retain)NSString * desc;

@end

加載操作將類似於此:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1]; 
Row *myRow = [[Row alloc] init]; 


for (int i=0; i<10; i++) 
{ 
    myRow.PK = i; 
    myRow.desc = [[NSString alloc] initWithFormat:@"Hello: %d", i]; 
    [array addObject:myRow]; 
} 
[myRow release]; 

for (int i=0; i < [array count]; i++) 
{ 
    Row *myNrow = [array objectAtIndex:i] ; 
    NSLog (@"%@ %d", [myNrow desc], [myNrow PK]); 
    myNrow = nil; 
} 

當然第一個for循環將從SELECT語句的循環。其他循環(或該循環的元素)將在cellInRowIndex方法中呈現數據。

我有一個關於內存泄漏的問題。上面的代碼是否有內存泄漏? Row類的decs字符串屬性被聲明爲(保留)。它不應該放在某個地方嗎?

謝謝

回答

1

您應該釋放要放入myRow.desc的字符串。你可以改變

myRow.desc = [[NSString alloc] initWithFormat:@"Hello: %d", i]; 

要麼

myRow.desc = [[[NSString alloc] initWithFormat:@"Hello: %d", i] autorelease]; 

myRow.desc = [NSString stringWithFormat:@"Hello: %d", i]; 

編輯:如果你想使用一箇中間的NSString(如你在註釋中),你可以要麼這樣做:

NSString *foo = [[NSString alloc] initWithFormat:@"Hello: %d", i]; 
myRow.desc = foo; 
[foo release]; 

或:

NSString *foo = [NSString stringWithFormat:@"Hello: %d", i]; 
myRow.desc = foo; 

注意,在第二個例子中富已經被自動釋放,所以你不能釋放它。

+0

謝謝。我有這樣的聲明: NSString * foo; 是否也應該這樣做: 富= [NSString的initWithFormat:@ 「你好%d」,我] 或 富= [[[的NSString頁頭] initWithFormat:@ 「你好%d」,我]自動釋放] 現在我有這個: foo = [[NSString alloc] initWithFormat:@「Hello%d」,d]; ... [foo發佈] – leon 2009-10-13 01:30:50

+0

嘗試修復格式化.... 謝謝。我有這樣的聲明: NSString * foo; 我是否也應該這樣做:

 foo = [NSString initWithFormat: @"Hello %d", i] or foo = [[[NSString alloc] initWithFormat:@"Hello %d", i] autorelease] Now I have this: foo = [[NSString alloc] initWithFormat: @"Hello %d", d]; ... [foo release] 
leon 2009-10-13 01:32:35