2011-02-18 135 views
0

我已經使用這段代碼從plist中加載數據。iPhone:變量範圍問題

-(void)loadOrCreateData { 
    NSLog(@"Start loadOrCreateData"); 
    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    { 
     NSLog(@"File Exists.. Loading from plist File"); 
     NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath]; 
     font = [array objectAtIndex:0]; 
     background = (NSString *)[array objectAtIndex:1]; 
     animation = [array objectAtIndex:5]; 
     [array release]; 
     NSLog(@"Loading Done!"); 
    } 
    else 
    { 
     NSLog(@"File does not exist.. Creating new plist File"); 
     font = @"Georgia-BoldItalic"; 
     background = @"monalisa.jpeg"; 
     animation = @"103"; 
     [self saveData]; 
    } 

    NSLog(@"Finish loadOrCreateData"); 
} 

- (NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; 
} 

- (void)saveData { 
    NSMutableArray *array = [[NSMutableArray alloc] init]; 
    [array addObject:font]; 
    [array addObject:background]; 
    [array addObject:animation]; 
    [array writeToFile:[self dataFilePath] atomically:YES]; 
    [array release]; 
} 

當沒有plist文件獲取數據時,第一次加載的時候一切正常。但在第二次加載時,當我嘗試使用loadOrCreate方法之外的加載數據時,應用程序崩潰。由於某些原因,在loadOrCreate方法之外訪問時,字體,背景和動畫中的數據不可用。變量 - 字體,背景和動畫在.h文件中聲明爲NSStrings,因此應該是全局可用的嗎?你能告訴我這是什麼原因嗎?

回答

2

您必須保留該對象。

font = [[array objectAtIndex:0] retain]; 
    background = (NSString *)[[array objectAtIndex:1] retain]; 
    animation = [[array objectAtIndex:5] retain]; 
... 
    font = [@"Georgia-BoldItalic" retain]; 
    background = [@"monalisa.jpeg" retain]; 
    animation = [@"103" retain]; 

注意:如果您要加載數據多次,那麼不要忘記在設置它們之前釋放值。

編輯:

-(void)loadOrCreateData { 
    [font release]; 
    [background release]; 
    [animation release]; 

    NSLog(@"Start loadOrCreateData"); 
    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    { 
     NSLog(@"File Exists.. Loading from plist File"); 
     NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath]; 
     font = [[array objectAtIndex:0] retain]; 
     background = (NSString *)[[array objectAtIndex:1] retain]; 
     animation = [[array objectAtIndex:5] retain]; 
     [array release]; 
     NSLog(@"Loading Done!"); 
    } 
    else 
    { 
     NSLog(@"File does not exist.. Creating new plist File"); 
     font = [@"Georgia-BoldItalic" retain]; 
     background = [@"monalisa.jpeg" retain]; 
     animation = [@"103" retain]; 
     [self saveData]; 
    } 

    NSLog(@"Finish loadOrCreateData"); 
} 
+0

如果字體,背景,動畫是高德,那麼你必須釋放他們的dealloc(就像你寫的)。如果它們是靜態全局變量,則不要釋放它們。 – Max 2011-02-18 04:16:15