RemoveObjectAtIndex calls the "message sent to the freed instance",

I am converting some code to ARC. The code looks for an element in NSMutableArray, then finds, deletes, and returns that element. The problem is that the element is immediately freed after removing "removeObjectAtIndex":

- (UIView *)viewWithTag:(int)tag { UIView *view = nil; for (int i = 0; i < [self count]; i++) { UIView *aView = [self objectAtIndex:i]; if (aView.tag == tag) { view = aView; NSLog(@"%@",view); // 1 (view is good) [self removeObjectAtIndex:i]; break; } } NSLog(@"%@",view); // 2 (view has been deallocated) return view; } 

When I run it, I get

 *** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0 

in the second log statement.

Pre-ARC, I was careful to save the object before calling removeObjectAtIndex :, and then to automatically alert it. How to tell ARC about the same?

+6
source share
1 answer

Declare a UIView *view link using the __autoreleasing classifier, for example:

 - (UIView *)viewWithTag:(int)tag { __autoreleasing UIView *view; __unsafe_unretained UIView *aView; for (int i = 0; i < [self count]; i++) { aView = [self objectAtIndex:i]; if (aView.tag == tag) { view = aView; //Since you declared "view" as __autoreleasing, //the pre-ARC equivalent would be: //view = [[aView retain] autorelease]; [self removeObjectAtIndex:i]; break; } } return view; } 

__autoreleasing will give you exactly what you want, because when you assign it, the new pointer is saved, auto-implemented, and then stored in lvalue.

See link ARC

+5
source

Source: https://habr.com/ru/post/900175/


All Articles