2011-12-15 49 views
0

比較我目前用繩子在Mac OS X的NSString中的NSTimer「循環」

我想請與循環比較掙扎(在我的情況下,我選擇了一個定時器),如果一個文件改變它的大小。 要做到這一點我做了以下內容:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    fileSize = [[NSString stringWithFormat:@""] retain]; 
    fileSizeSrc = [[NSString stringWithFormat:@""] retain]; 

    fileManager = [NSFileManager defaultManager]; 
    fileAtts = [fileManager attributesOfItemAtPath:@"~/Desktop/test.txt" error:NULL]; 
    fileSizeSrc = [NSString stringWithFormat:@"%llu", [fileAtts fileSize]]; 
    [self startWatching:nil]; 
} 
- (void)startWatching:(id)sender 
{ 
    timer = [NSTimer scheduledTimerWithTimeInterval:2 
              target:self 
              selector:@selector(checkForUpdates) 
              userInfo:nil 
              repeats:YES]; 
    [timer fire]; 
} 
- (void)checkForUpdates 
{ 
    fileAtts = [fileManager attributesOfItemAtPath:@"~/Desktop/test.txt" error:NULL]; 
    fileSize = [NSString stringWithFormat:@"%llu", [fileAtts fileSize]]; 
    if([fileSize isEqualToString:fileSizeSrc]) 
    { 
     NSLog(@"%@", fileSize); 
     fileSizeSrc = [NSString stringWithFormat:@"%@", fileSizeSrc]; 
    } 
} 
- (void)applicationWillTerminate:(NSNotification *)notification 
{ 
    [timer invalidate]; 
    timer = nil; 
    [fileSize release]; 
    [fileSizeSrc release]; 
} 

我可以只檢查大小一次。 所以我的代碼運行時,它給了我一個輸出兩秒後(當選擇被炒魷魚第二次)我的程序與EXC_BAD_ACCESS

結束,當我嘗試通過更改爲if(![fileSize isEqualToString:fileSizeSrc])反轉if()語句它在啓動後立即終止。

我保留,然後在第一次發生問題後釋放字符串,因爲它在我身上發現,我必須這樣做。

我希望有人能幫助我! 非常感謝, 祝賀Julian。

回答

0

如果你不使用自動保留計數器(在iOS5中提供):

你需要創建一個將保留您的信息(容易)或保留它自己的屬性。

@interface ... 
{ 
    NSString* _fileSizeSrc; 
} 

@property (retain)NSString* fileSizeSrc; 

@end 

@implementation ... 
@synthesise fileSizeSrc = _fileSizeSrc; 


... 


@end 

設置你需要寫屬性:

self.fileSizeSrc = [NSString stringWithFormat:@"%llu", [fileAtts fileSize]]; 

和兩件事:

  1. dont't忘記設置屬性爲nil在-(void) dealloc
  2. 如果你創建一個屬性 - 不直接與變量一起工作。