可能的View缓存问题?

时间:2009-11-03 13:56:51

标签: iphone cocoa-touch iphone-sdk-3.0

我正在构建一个iphone应用程序,我有一个表格视图,其中包含单元格内的一些文本字段,字段的内容在viewWillAppear中设置(它是一个分组的TableView,其中3个字段始终相同)。从getter方法检索文本字段的内容,这些方法返回各种类变量的值。

我遇到的问题是getter似乎返回原始值,而不是setter方法修改的值。类变量是NSMutableString。视图是否可以缓存方法调用?

//header file
@implementation ManageWorkoutViewController : UIViewController {
    NSMutableString *workoutDifficulty;
}

-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)getWorkoutDifficulty;

@end



//implementation file
-(NSString *)getWorkoutDifficulty {

    if (nil == workoutDifficulty) {
        workoutDifficulty = [NSMutableString stringWithString:@"Easy"];
    }

    NSLog(@"getter: Returning workoutDifficulty as: %@", workoutDifficulty);

    return workoutDifficulty;

} //end getWorkoutDifficulty



-(void)setWorkoutDifficulty:(NSString *)value {

    workoutDifficulty = [NSString stringWithFormat:@"%d", value];
    NSLog(@"setter: workoutDifficulty set as: %@", workoutDifficulty);

}//end setWorkoutDifficulty


//elsewhere in the implementation another table view is 
//pushed onto the nav controller to allow the user to pick
//the difficulty.  The initial value comes from the getter
workoutDifficultyController.title = @"Workout Difficulty";
[workoutDifficultyController setOriginalDifficulty:[self getWorkoutDifficulty]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[(UINavigationController *)self.parentViewController pushViewController:workoutDifficultyController 
                                                               animated:YES];

//then in that workoutDifficultyController it calls back into the first controller to set the selected value:
[manageWorkoutController setWorkoutDifficulty:selectedDifficulty];

2 个答案:

答案 0 :(得分:1)

你这里有很多问题。首先,您正在错误地创建访问者。特别引起麻烦的问题是这一行:

workoutDifficulty = [NSString stringWithFormat:@"%d", value];

value在这里是一个NSString。您应该收到关于此的警告。我相信“Typecheck Calls to printf / scanf”默认打开,应该抓住这个。 workoutDifficulty被设置为一些随机数(可能取自value的前4个字节)。

这是你的意思。我可能会将workoutDifficulty切换到枚举,但我保留一个NSString以保持与代码的一致性。我也这样做没有属性,因为你做了,但我会在这里使用一个属性。

//header file
@implementation ManageWorkoutViewController : UIViewController {
    NSString *_workoutDifficulty;
}

-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)workoutDifficulty;  // NOTE: Name change. "getWorkoutDifficulty" is incorrect.

@end

//implementation file
-(NSString *)workoutDifficulty {
    if (nil == workoutDifficulty) {
        _workoutDifficulty = [@"Easy" retain];
    }

    NSLog(@"getter: Returning workoutDifficulty as: %@", _workoutDifficulty);

    return _workoutDifficulty;  
} //end workoutDifficulty

-(void)setWorkoutDifficulty:(NSString *)value {
    [value retain];
    [_workoutDifficulty release];
    _workoutDifficulty = value;
    NSLog(@"setter: workoutDifficulty set as: %@", _workoutDifficulty);    
}//end setWorkoutDifficulty

答案 1 :(得分:0)

每当您将其设置为新值(并释放旧值)时,您必须保留workoutDifficulty