我想知道ios属性原子非原子线程安全而不是线程安全

时间:2015-09-07 18:57:22

标签: ios objective-c xcode

这里的原子/非原子属性:

@property (nonatomic,strong) NSString* firstName;
@property (atomic,strong) NSString* lastName;

使用setter / getters:

-(void)setFirstName:(NSString *)fname{
    NSLog(@"set self.firstname: %@ ",fname);
    self.firstName = [fname uppercaseString];
}

-(NSString *)firstName{
    NSLog(@" get self.firstname: %@ ",self.firstName);
    return self.firstName;
}

-(void)setLastName:(NSString *)lName{
    NSLog(@"set self.laststname: %@ ",lName);
    self.lastName = lName.uppercaseString;
}

-(NSString *)lastName{
    NSLog(@" get self.lastname: %@ ",self.firstName);
    return self.lastName;
}

当试图从异步排队的块中修改/访问时,它崩溃了:

-(void)viewWillAppear:(BOOL)animated
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        self.firstName = @"f1";
        self.lastName = @"l1";
    });

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        self.firstName = @"f2";
        self.lastName = @"l3";
    });

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        self.firstName = @"f3";
        self.lastName = @"l3";
    });

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0),^{
      NSLog(@"first : %@ \t last : %@",self.firstName,self.lastName);
    });
}

@end

使用上述代码,问题是:

  1. 为什么会崩溃。
  2. 处理多个线程时原子/非原子属性之间的区别

1 个答案:

答案 0 :(得分:0)

当然它崩溃了。看看你在做什么:你实现了setter,setter再次调用了setter。再次调用setter,依此类推等等。这与原子/非原子无关,与你如何调用它无关。 任何调用你的setter或getter都会崩溃,因为他们称自己为无限递归。

顺便说一句。这是粗心的:

NSLog(@" get self.lastname: %@ ",self.firstName);

顺便说一句。许多问题都讨论了原子/非原子属性的含义。