1

전역으로 정의되고 UITableViewController의 ViewDidLoad에서 초기화되는 클래스 인스턴스가있는 iPhone 애플리케이션에서 작업합니다.Objective C 클래스 인스턴스 속성이 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 내가 foo는 공개하고 있지 않다

-(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에서 뭔가가 누락 되었습니까?

UPDATE는

나는 발견 데이터베이스에서 속성을 채우는 경우 데이터를 보관 유지하는, 유지 추가하여 :

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

이 맞거나 내가 다른 뭔가를 놓친 거지?

답변

1

여기서 문제는 prop1을 속성으로 사용하지 않고 클래스의 변수로 사용한다는 것입니다. 당신은이 다른 이름을 줄 수 있어야합니다. 그것은 변수 이름의 시작 부분에 밑줄을 넣어 관례 : 실제로 속성을 사용하는

foo.h

NSString *_prop1; 

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

이제 foo.m

@synthesize prop1 = _prop1; 

, getters 및 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 

충돌 및 기타 나쁜 행동으로 이어집니다.

업데이트로 인해 충돌이 방지되지만 두 번 이상 실행하면 메모리가 누출됩니다.

+0

우수. 답변 해 주셔서 감사합니다. – jfuhr

관련 문제