iOS — distinguish an NSDictionary from an NSMutableDictionary?

后端 未结 6 1208
佛祖请我去吃肉
佛祖请我去吃肉 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:52

    If you need to guarantee that a dictionary is mutable, you should:

    • create it as mutable if you are the one initializing it
    • turn it into a mutable instance with the -[NSDictionary mutableCopy] method, for example if you're calling an API that returns an NSDictionary. Note that mutableCopy increments the retain count; you need to release this instance if you are using manual reference counting.

    Determining whether an NSDictionary is mutable before attempting to modify its keys and/or values can be considered an example of a code smell, indicating that there's a deeper problem that should be solved. In other words, you should always know whether a given dictionary instance is NSDictionary or NSMutableDictionary. The code should be clear on that point.

提交回复
热议问题