关于C#:我想了解ios属性原子非原子线程安全而不是线程安全

I want to know about ios property atomic nonatomic thread safe and not thread safe

原子/非钛属性如下:

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

使用setter/getter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-(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;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-(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

对于上述代码,问题是:

  • 为什么它会崩溃。
  • 处理多个线程时原子/非原子属性之间的区别是什么?

  • 当然是坠毁了。看看你在做什么:你实现了setter,setter再次调用setter。它再次调用setter,等等。这与原子/非原子无关,也与你如何称呼它无关。任何调用都会导致setter或getter崩溃,因为它们以无限递归的形式调用自己。

    顺便说一句,这太粗心了:

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

    顺便说一下,原子/非原子性质的含义在许多问题中都有讨论。