简体   繁体   中英

NSInvocation trigger memory leak

i test in NSInvocation with ARC, but it trigger memory leaks. In MRC, it work well. i do not know why.

- (NSArray *)a:(NSString *)a b:(NSString *)b c:(NSString *)c
{
    return  @[a, b, c];
}
- (void)testNSInvocation
{
    NSMethodSignature *sig = [self methodSignatureForSelector:@selector(a:b:c:)];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

    [inv setTarget:self];
    [inv setSelector:@selector(a:b:c:)];

    NSString *a = @"a", *b = @"b", *c = @"c";
    [inv setArgument:&a atIndex:2];
    [inv setArgument:&b atIndex:3];
    [inv setArgument:&c atIndex:4];

    [inv retainArguments];
    [inv invoke];

    NSArray *ret;
    [inv getReturnValue:&ret];//this is problem,but why?
    NSLog(@"ret:%@", ret);
} 

I find answer in stackOverflow. The problem is getReturnValue:, it just copies the bytes of the return value into the given memory buffer, regardless of type. It doesn't know or care about memory management if the return type is a retainable object pointer type. Since ret is a __strong variable of object pointer type, ARC assumes that any value that has been put into the variable has been retained, and thus will release it when it goes out of scope. That is not true in this case, so it crashes. (Also, the array that had ret originally point to will be leaked, since getReturnValue: overwrites that value without releasing it. Why you even made that variable point to an object in the first place is beyond me.) NSInvocation returns value but makes app crash with EXC_BAD_ACCESS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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