【问题标题】:NSString comparing in NSTimer "loop"NSTimer“循环”中的 NSString 比较
【发布时间】:2011-12-15 04:10:21
【问题描述】:

我目前正在为 Mac OS X 中的字符串比较而苦苦挣扎

如果文件改变了它的大小,我想用一个循环检查(在我的例子中我选择了一个计时器)。 为此,我执行以下操作:

- (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];
}

我可以检查一次尺寸。 So when my code runs, it gives me an output and two seconds later (when the selector gets fired the second time) my program terminates with EXC_BAD_ACCESS

当我尝试通过更改为 if(![fileSize isEqualToString:fileSizeSrc]) 来反转 if() 语句时,它会在启动后立即终止。

我在第一次出现问题后保留并释放字符串,因为我突然意识到我必须这样做。

我希望有人可以帮助我! 非常感谢, 问候,朱利安。

【问题讨论】:

    标签: macos cocoa nsstring nstimer


    【解决方案1】:

    如果你不使用自动保留计数器(在 ios5 中可用):

    您需要创建一个属性来保留您的信息(简单)或自己保留。

    @interface ...
    {
      NSString* _fileSizeSrc;
    }
    
    @property (retain)NSString* fileSizeSrc;
    
    @end
    
    @implementation ...
    @synthesise fileSizeSrc = _fileSizeSrc;
    
    
    ...
    
    
    @end
    

    设置你需要写的属性:

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

    还有两件事:

    1. 不要忘记在-(void) dealloc 中将属性设置为 nil
    2. 如果您创建属性 - 不要直接使用变量。

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多