【问题标题】:Objective C Class instance properties deallocating in UITableViewController在 UITableViewController 中解除分配的 Objective C 类实例属性
【发布时间】:2012-04-25 08:09:57
【问题描述】:

在一个 iPhone 应用程序上工作,我有一个类实例,该类实例被定义为全局并在 ViewDidLoad 中为 UITableViewController 初始化。

当它到达 cellForRowAtIndexPath 时,实例属性被释放并显示在调试器中。

正在从数据库中加载属性。

Foo.h

NSString *prop1;

@property(nonatomic, retain)NSString *prop1;
-(void)shouldLoadProperties;

Foo.m

@synthesize prop1;

-(void)shouldLoadProperties {
    <FMDatabase stuff here>

    FMResultSet *rs = [self executeQuery:sql];
    prop1 = [rs stringForColumn:@"col1"];  //loads db value "Test" into prop1
}

tableview 控制器:

TestTableViewController.h

Foo *foo;

TestTableViewController.m

-(void)viewDidLoad {
   foo = [[[Foo alloc] init] retain];
   [foo shouldLoadProperties];

   //Breakpoint here shows that foo.prop1 is set to "Test"

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   //foo is is still allocated, but foo.prop1 has been 
   //deallocated;  shows as <freed object>  

  NSLog(@"Prop 1 is %@", foo.prop1);  //throws exception


}

我没有释放 foo,那么为什么这些属性会自行释放呢?我是否遗漏了 Foo 中的某些内容以挂起属性,直到实例被释放?

更新

我发现通过在从数据库中填充属性时添加保留,数据可以保存:

 prop1 = [[rs stringForColumn:@"col1"] retain];

这是正确的还是我错过了什么?

【问题讨论】:

    标签: iphone objective-c memory-management retain reference-counting


    【解决方案1】:

    这里的问题是您没有将prop1 用作属性,而是用作类中的变量。你可以而且应该给这些不同的名字。习惯上在变量名的开头加下划线:

    foo.h

    NSString *_prop1;
    
    @property(nonatomic, retain)NSString *prop1;
    -(void)shouldLoadProperties;
    

    foo.m

    @synthesize prop1 = _prop1;
    

    现在,要实际使用您的属性,请使用 getter 和 setter。这将保留您的价值并在适当的时候释放它。

    [self setProp1:[rs stringForColumn:@"col1"]];  //loads db value "Test" into prop1
    

    self.prop1 = [rs stringForColumn:@"col1"];  //loads db value "Test" into prop1
    

    都是有效的并且彼此等价的。

    _prop1 = [rs stringForColumn:@"col1"];  //loads db value "Test" into prop1
    

    会导致崩溃等不良行为。

    您的更新将防止崩溃,但如果您多次执行此操作会泄漏内存。

    【讨论】:

    • 优秀。感谢您的回复!
    猜你喜欢
    • 2012-03-03
    • 2012-02-02
    • 2010-12-05
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多