简体   繁体   English

ARC和非ARC框架之间的内存管理

[英]Memory management between ARC and non-ARC frameworks

I have a framework A which is ARC. 我有一个框架A,它是ARC。 This consumes some API's from non ARC framework B. 这消耗了非ARC框架B的一些API。

Framework B sample code (non ARC): 框架B示例代码(非ARC):

@interface Settings : NSObject {
    NSDictionary* settings;
}
- (NSString*)stringForKey:(NSString*)key;
@end
@implementation Settings
- (NSString*)stringForKey:(NSString*)key {
    return [settings objectForKey: key];
}
@end

Framework A sample code (ARC): 框架示例代码(ARC):

{
    // ...
    SEL stringForKeySelector = @selector(stringForKey:);
    NSMethodSignature *stringForKeySignature = [[Settings class] instanceMethodSignatureForSelector:stringForKeySelector];
    NSInvocation *stringForKeyInvocation = [NSInvocation invocationWithMethodSignature:stringForKeySignature];
    [stringForKeyInvocation setSelector:stringForKeySelector];
    [stringForKeyInvocation setTarget:SettingsObject];

    NSString *Key = @"KEY";
    [stringForKeyInvocation setArgument:& Key atIndex:2];
    [stringForKeyInvocation invoke];

    NSString *value = nil;
    [stringForKeyInvocation getReturnValue:& value];

    // ...
}

Object from settings dictionary gets released after executing above code in framework A. 在框架A中执行上述代码后,将释放设置字典中的对象。

Any help is appreciated in advance. 任何帮助都需要提前感谢。

Answer: Thanks Chuck for pointing out problems with NSInvocation and ARC. 答:感谢Chuck指出了NSInvocation和ARC的问题。 I got around this problem by returning basic data types. 我通过返回基本数据类型解决了这个问题。

This has nothing to do with memory management between ARC and non-ARC code. 这与ARC和非ARC代码之间的内存管理无关。 Instead, this is because NSInvocation does not work very cleanly with ARC. 相反,这是因为NSInvocation与ARC不能很好地协同工作。 It's usually preferable to avoid NSInvocation anyway, and doubly so with ARC. 无论如何,通常最好避免使用NSInvocation,而对于ARC则最好避免这种情况。 There is usually a better choice for anything you'd use NSInvocation for. 对于要使用NSInvocation的任何事物,通常都有更好的选择。 If you must use NSInvocation, you'll need to remember that it just deals with raw byte blobs and doesn't handle object ownership at all, so passing an ARC-managed pointer is not kosher. 如果必须使用NSInvocation,则需要记住,它仅处理原始字节blob,并且根本不处理对象所有权,因此传递ARC管理的指针不会引起任何争议。 You'll want to have the return-value variable be a void pointer, and then use a bridging cast to assign it to a normal object-type variable. 您将需要让return-value变量成为void指针,然后使用桥接强制转换将其分配给普通的对象类型变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM