0

I want to directly assign value to an ivar of class concurrently.

I know there will be problem using setter method (self.target = ...) since ARC inner retain and release stuff for strong property. But I'm trying to use ivar.

  1. Is it because the implicit qualifier __strong? But _target is an ivar, so it won't be released outside each dispatch_async block, right?

  2. And if you make the string shorter, iOS system will apply a tagged pointer to _target, why in this case no bad access error happens anymore?

@interface ClassA ()
@property (nonatomic, strong) NSString *target;
@end

@implementation ClassA
- (void)test {
    dispatch_queue_t queue = dispatch_queue_create("parallel", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10000 ; i++) {
        dispatch_async(queue, ^{
            _target = [NSString stringWithFormat:@"aaaaaaaaaaaaaa-%d",i];  //Bad Access Error in releasing, an NSCFString
            //_target = [NSString stringWithFormat:@"aa-%d",i];  //No problem, an NSTaggedPointerString
        });
    }
}
@end

int main(int argc, char * argv[]) {
    ClassA *obj = [[ClassA alloc] init];
    [obj test];
    return 0;
}
刘maxwell
  • 187
  • 10

1 Answers1

2

Using ivar doesn't makes difference: compiler just add retain/release instead of you. You need unsafe_unretained property to disable insertion of retain/release

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22
  • I can understand retain, for [NSString stringWithFormat:...] will be autoreleased later, so _target has to retain it. But where does release happen? When it go outside the block scope? But _target is an instance variable, why could it be released outside the block scope? – 刘maxwell Jul 09 '19 at 07:31
  • According to some blog, setter method is the spot where new value retaining and old value releasing happen. But I also learn that assign value to a strong variable will invoke `objc_storeStrong` function, where implicit retain and release codes locate. So where on earth is retain/release happen, setter or process of value assign to ivar? – 刘maxwell Jul 09 '19 at 10:08
  • @刘maxwell, in the assign new value will be retained and old will be released, you can look at inserted retain/release calls in the assembler – Cy-4AH Jul 09 '19 at 10:17