开发者

What's safe to assume about the NSMutableArray / NSArray class cluster?

I know you shouldn't use this to decide whether or not to change an array:

if ([possiblyMutable isKindOfClass:[NSMutableArray class]])

But say I'm writing a method and need to return either an NSMutableArray or an NSArray, depending on the mutability of possiblyMutable. The class using my method already knows whether or not it's acceptable to change the returned array. Whether or not it's acceptable to change the returned array directly correlates with whether or not it's acceptable to change possiblyMutable.

In that specific case, is this code safe? It seems to me that if it's not acceptable to change the array, but we accidentally get开发者_StackOverflow社区 a mutable array, it's ok, because the class using my method won't try to change it. And if it is acceptable to change the array, then we will always get possiblyMutable as an NSMutableArray (though this is the part I'm not entirely clear on).

So... safe or not? Alternatives?


No. Not safe at all.

If you do:

NSMutableArray * ma = [NSMutableArray arrayWithObject:@"foo"];
NSArray * aa = [NSArray arrayWithObject:@"foo"];

NSLog(@"Mutable: %@", [ma className]);
NSLog(@"Normal: %@", [aa className]);

Then you get:

2010-04-05 13:17:26.928 EmptyFoundation[55496:a0f] Mutable: NSCFArray
2010-04-05 13:17:26.956 EmptyFoundation[55496:a0f] Normal: NSCFArray

You also can't do:

NSLog(@"Mutable add: %d", [ma respondsToSelector:@selector(addObject:)]);
NSLog(@"Normal add: %d", [aa respondsToSelector:@selector(addObject:)]);

Because this logs:

2010-04-05 13:18:35.351 EmptyFoundation[55525:a0f] Mutable add: 1
2010-04-05 13:18:35.351 EmptyFoundation[55525:a0f] Normal add: 1

The only ways to guarantee you have a mutable array are to take the -mutableCopy of an existing array or if the return type of a function/method guarantees the array will be mutable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜