iOS — distinguish an NSDictionary from an NSMutableDictionary?

后端 未结 6 1131
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 14:34

I have the following code fragment:

NSString* value = @\"value\";
NSString* key = @\"key\";
NSMutableDictionary* foo = [NSMutableDictionary dictionary];
NSDictio         


        
6条回答
  •  一向
    一向 (楼主)
    2021-01-21 14:56

    Honestly, you can't easily tell the difference without a @try block. Standard practice is as follows:

    • If you want to check whether it's mutable in order to avoid someone passing you an unexpectedly mutable object and then mutating it out from under you, copy the dictionary. If it's really non-mutable, the frameworks will optimize that into a retain. If it really was mutable, then you probably wanted a copy anyway.
    • If you need a mutable dictionary, declare your method parameters to require one. Simple as that.
    • In general, trust that people won't try to mutate objects unless specifically told they were mutable.

提交回复
热议问题