【问题标题】:iPhone SDK: loading UITableView from SQLite - creating array from SQLiteiPhone SDK:从 SQLite 加载 UITableView - 从 SQLite 创建数组
【发布时间】:2010-12-06 03:37:38
【问题描述】:

这是iPhone SDK: loading UITableView from SQLite的后续跟进

我打算使用以下代码将 SQL 数据加载到数组中。数组的每个元素都是代表每个数据库条目的类:

@interface 行:NSObject { 国际PK; NSString *desc;

}

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

@结束

加载操作将与此类似:

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 字符串属性声明为 (retain)。不应该在某个地方发布吗?

谢谢

【问题讨论】:

    标签: iphone sqlite retain objective-c-2.0


    【解决方案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;
    

    请注意,在第二个示例中 foo 已经自动释放,因此您不能释放它。

    【讨论】:

    • 谢谢。我有这样的声明: NSString *foo;我是否也应该这样做: foo = [NSString initWithFormat: @"Hello %d", i] 或 foo = [[[NSString alloc] initWithFormat:@"Hello %d", i] autorelease] 现在我有了这个: foo = [[NSString alloc] initWithFormat:@"Hello %d", d]; ... [foo 发布]
    • 正在尝试修复格式......谢谢。我有这样的声明: NSString *foo;我是否也应该这样做:
       foo = [NSString initWithFormat: @"Hello %d", i] 或 foo = [[[NSString alloc] initWithFormat:@"Hello %d", i] autorelease] 现在我有了这个: foo = [[NSString alloc] initWithFormat: @"Hello %d", d]; ... [foo 发布] 
    猜你喜欢
    • 2010-12-05
    • 2011-08-30
    • 2011-03-27
    • 1970-01-01
    • 2013-09-09
    • 2011-08-30
    • 2016-03-01
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多