Cocoa: Testing to find if an NSString is immutable or mutable?

后端 未结 3 1821
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 03:26

This produces an immutable string object:

NSString* myStringA = @\"A\";  //CORRECTED FROM: NSMutableString* myStringA = @\"A\";

This produc

3条回答
  •  离开以前
    2020-12-18 03:49

    If you want to check for debugging purposes the following code should work. Copy on immutable object is itself, while it's a true copy for mutable types, that's what the code is based on. Note that since it's calling copy it's slow, but should be fine for debugging. If you'd like to check for any other reasons than debugging see Rob answer (and forget about it).

    BOOL isMutable(id object)
    {
       id copy = [object copy];
       BOOL copyIsADifferentObject = (copy != object);
       [copy release];
       return copyIsADifferentObject;
    }
    

    Disclaimer: of course there is no guarantee that copy is equivalent with retain for immutable types. You can be sure that if isMutable returns NO then it's not mutable so the function should be probably named canBeMutable. In the real world however, it's a pretty safe assumption that immutable types (NSString,NSArray) will implement this optimization. There is a lot of code out including basic things like NSDictionary that expects fast copy from immutable types.

提交回复
热议问题