0

I just want to know the tech inside.

Does it enumerate all key/value s or copy method is thread safe?

If I'm doing [dict copy](dict is a NSMutableDictionary) on a background thread, and update dict on main thread, will it crash?

code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    for (int i = 0; i < 1000; i++) {
        [self.dict addEntriesFromDictionary:@{@"key": [NSObject new], @"key3": [NSObject new]}];
    }
});
for (int i = 0; i < 1000; i++) {
    [self.dict copy];
}
Ypy
  • 56
  • 5
  • Possible duplicate of [NSMutableDictionary thread safety](http://stackoverflow.com/questions/1986736/nsmutabledictionary-thread-safety) – Andrew Jul 12 '16 at 03:35
  • Can you show an example of the second question? – AdamPro13 Jul 12 '16 at 03:38
  • It's important to note that `copy` on an `NSDictionary`, `NSMutableDictionary`, and other Foundation storage classes (`NSArray`, `NSSet`, or their mutable subclasses) does a shallow copy, not a deep copy of the structure. That means it will create a copy of the container object, NOT what is in the container. It will also `+1` all reference counts of the objects in those containers. – AdamPro13 Jul 12 '16 at 03:38
  • @AdamPro13 I have update the question for the second question. – Ypy Jul 12 '16 at 03:46
  • The method `copy` is non-mutating. That means just calling `copy` on a dictionary won't change that dictionary. You will want to use the returned object in some way. Just calling `copy` and not using the returned object is a waste of clock cycles. – AdamPro13 Jul 12 '16 at 03:58
  • @AdamPro13 I know. The code is just an example to show what I want to know. If I do this, there will be random crash. – Ypy Jul 12 '16 at 04:15

0 Answers0