【发布时间】:2012-03-14 17:47:05
【问题描述】:
当属性具有自定义命名的 getter 和 setter 时,我正在制作一个实用程序来获取/设置属性值。您可以在第 279 行 here 看到完整的上下文。相关的sn-p在这里:
- (id) getFrom:(id) object {
NSMethodSignature *methodSig = [[object class] instanceMethodSignatureForSelector:[self getter]];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:methodSig];
[inv setSelector:[self getter]];
[inv setTarget:object];
[inv invoke];
if ([self isObject]) {
id returnValue;
[inv getReturnValue:&returnValue];
return returnValue;
} else {
void *buffer;
NSUInteger length = [methodSig methodReturnLength];
buffer = (void *)malloc(length);
[inv getReturnValue:buffer];
NSValue *value = [NSValue valueWithBytes:buffer objCType:[methodSig methodReturnType]];
//FIXME: Memory leak for buffer! But if we free it, [value getValue:] is a dangling pointer.
//free(buffer)
return value;
}
}
问题是当属性是标量时,我想返回一个 NSValue(很像 Key-Value 编码)。但是,NSInvocation 的返回值是通过引用返回的,并且根据the apple documentation(见底部),当 NSValue 仍然存在时,我无法释放与标量关联的内存——但我正在返回 NSValue,所以我不知道什么时候释放内存。
我是否阅读了错误的文档? NSValue 会以某种方式自动处理吗?或者在这种情况下如何正确释放内存?
【问题讨论】:
标签: objective-c