我正在查看用于反序列化 JSON 响应的代码示例。最后一行 return [topics copy];
在返回之前复制数组。我查了一下原因,它是返回一个不可变的 NSArray。
但是,这是标准做法还是高度防御性编程?调用方法会将返回值分配给某些东西,如果它想将返回值分配给不可变的 NSArray ,它就会这样做。如果它将返回值分配给 NSMutableArray
那么它就会这样做。
所以我的问题是 - 是否有任何现实的场景可以防止不必要的后果?
// Returns array of @c NPTopic objects
- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
return nil;
}
NSDictionary *JSONDictionary = [super responseObjectForResponse:response data:data error:error];
if (!JSONDictionary) return nil;
// Note: the expected JSON format of this response is { data: [ { <a topic> }, { <another topic>} ], metadata: { ...} }
NSArray *JSONTopics = JSONDictionary[@"data"];
NSMutableArray *topics = [NSMutableArray array];
for (NSDictionary *JSONTopic in JSONTopics) {
// For each topic in JSON format, we can deserialize it from JSON to our desired model class using Mantle
NPTopic *topic = [MTLJSONAdapter modelOfClass:[NPTopic class] fromJSONDictionary:JSONTopic error:error];
if (!topic) return nil;
[topics addObject:topic];
}
*error = nil;
return [topics copy];
}
最佳答案
该副本返回的是 NSArray
,而不是 NSMutableAray
。问题是,如果返回一个 NSMutableAray
,它就可以被更改,这可能是一个问题,因为有多个指针指向它,一个指针进行更改,但另一个指针假设它是不可变的并且不会更改。
这是一个很好的做法。
不要对实际实现做出假设,有多种方式可以在不实际制作副本的情况下进行“复制”。在没有必要和证据的情况下担心性能被称为“过早优化”,许多人再次发出警告,其中包括著名的 Donald Knuth。
它确实应该具有返回类型 NSArray *
,而不是 id
,以便编译器可以捕获类型错误。
关于ios - 为什么此代码示例在返回之前进行复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371467/