2009-10-12 50 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