2011-10-27 2 views
6

일부 코드를 ARC로 변환 중입니다. 이 코드는 NSMutableArray에서 요소를 검색 한 다음 해당 요소를 찾아서 제거하고 반환합니다. 문제는 요소가 "removeObjectAtIndex"즉시 해제됩니다 있다는 것입니다 : 나는 그것을 실행하면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; 
} 

, 나는 두 번째 로그 문에

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

를 얻을.

Pre-ARC, 나는 removeObjectAtIndex :를 호출하기 전에 객체를 유지하고 나서 자동으로 릴리즈합니다. ARC에게 똑같은 일을 시키라고 어떻게 말합니까?

+0

'[자기 removeObjectAtIndex을 : 내가] 참조;'합니까? – hypercrypt

답변

5

지금처럼 __autoreleasing 규정과 UIView *view 참조를 선언 :

- (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 당신에게 을 줄 것이다 정확히 당신은 할당에 새로운 pointee이 유지되기 때문에, 오토 릴리즈 한 다음에 저장 원하는 lvalue.

ARC reference 무엇

+2

'__strong'이 기본값이라고 생각 했습니까? 어쨌든이 일을하지 않겠습니까? – Robert

+0

@Robert 죄송합니다, 업데이트되어 있습니다. –

+0

제이콥 감사합니다. 두 가지 : 1) iOS 4 호환성을 유지하기 위해 __weak 대신 __unsafe_unretained를 사용해야했습니다. 2) 해당 파일에 대해 ARC가 켜지지 않았 음을 나타냅니다. 멍청한 실수. 나는 "fno-obj-arc"를 대상 -> 빌드 단계 -> 소스 소스 섹션에서 제거해야했습니다. – lewisanderson

관련 문제