1

Obj-C와 Xcode에서 강하고 약한 참조가있는 딜레마가 있습니다. 내가 안으로 서로 상호 참조 두 개의 객체를 생성 할 때, 모든 약한 :Objective-C로 Xcode에서 ARC가 제대로 작동하지 않습니다.

Mouse *mouse = [[Mouse alloc] initWithComputer:nil]; 
Computer *computer = [[Computer alloc] initWithMouse:mouse]; 

NSLog(@"%@", computer.mouse); //prints legit address 

mouse = nil; //destroy the ONLY strong reference to Mouse 

NSLog(@"%@", computer.mouse); //still prints(holds) the same legit address 

마우스 전에 = 무기 호;

enter image description here

마우스 후 = 무기 호; Mouse 클래스 마우스, 마우스 computer.mouse가 해제되어야 할 때 여전히 같은 메모리 주소를 보유의 인스턴스에 "파괴"유일한 강한 참조 후

enter image description here

.

는 물론 엑스 코드 만 SWIFT에서 동일한 코드가 제대로 작동하고 메모리가 computer.mouse에 의해 개최되고 할당을 해제 그것을 전무

내를 Obj-C 코드와 아무 잘못인가? 내 Xcode는 최신 버전이지만 이전 버전에서는 Obj-c에서도 운이 없었습니다. 나는 어떤 도움을 주셔서 감사합니다. Computer.h

#import <Foundation/Foundation.h> 
@class Mouse; 

@interface Computer : NSObject 

@property (nonatomic, weak) Mouse *mouse; 

- (instancetype) initWithMouse: (Mouse *) userPutMouse ; 

@end 

Computer.m

#import "Computer.h" 
#import "Mouse.h" 

@implementation Computer 

- (instancetype) initWithMouse: (Mouse *) userPutMouse { 

    self = [super init]; 

    if (self) { 

     self.mouse = userPutMouse; 
     self.mouse.computer = self; 

    } 

    return self; 
} 

@end 

Mouse.h

#import <Foundation/Foundation.h> 
@class Computer; 

@interface Mouse : NSObject 

@property (nonatomic, weak) Computer *computer; 

- (instancetype) initWithComputer: (Computer *) userPutComputer; 

@end 

Mouse.m

: 여기

내 클래스입니다
#import "Mouse.h" 
#import "Computer.h" 

@implementation Mouse 

- (instancetype) initWithComputer: (Computer *) userPutComputer { 

    self = [super init]; 

    if (self) { 

     if (userPutComputer) { 
      self.computer = userPutComputer; 
     } 

    } 

    return self; 
} 

@end 

답변

4

자동으로 합성되는 getter는 자동 반환 풀로 반환하는 객체를 배치합니다. 그러므로 mouse에서 nil 로의 할당은 최종 소유 참조를 종료하지 않습니다. 당신이 어떤 것에 대한 참조를 소유 한 유일한 사람이라고 생각하지 말고, 당신이 적절한 행동을 취하도록하십시오.

Mouse *mouse; 
Computer *computer; 

@autoreleasepool { 

    mouse = [[Mouse alloc] initWithComputer:nil]; 
    computer = [[Computer alloc] initWithMouse:mouse]; 

    NSLog(@"%@", computer.mouse); //prints legit address 

    mouse = nil; //destroy **my** ONLY strong reference to Mouse 

} 

NSLog(@"%@", computer.mouse); //prints (null) 

을 ...뿐만 아니라 적절한 소유권이 경험적으로 발생 여부를 진단 할 결코 :

실험 시연,이 시도. 그렇기 때문에 retainCount 속성을 더 이상 사용할 수 없습니다.

EDIT : 확장 : getter에서 예상되는 전통적인 동작은 적어도 현재 호출 스택만큼 오래 지속되도록 보장되지 않는 비공유 참조를 반환하는 것입니다. 이것은 ARC 이전의 날에는 인수를 속성으로 제공하기 위해 getter를 직접 사용할 수 있습니다 (이 경우 호출자에게 메모리 관리를 부담시키지 않음). 호출자가 일시적으로 보유 할 수있는 항목을 가져 오는 경우에도 원래 소유자는 그 사이에 할당이 해제됩니다 (즉, 스택에있는 것처럼 고전적인 autorelease 풀 사용법이 약간 작동합니다).그런 다음 ARC는 구식 규칙을 구현하지만 자동으로 완벽한 상호 운용성을 제공합니다.

+0

대단히 감사합니다! 이제는 분명합니다! – Maxim