일반적으로 원하는 것이기 때문에 Strong이 기본값이지만 컴파일러는 ARC를 사용하여 개체의 수명을 분석하고 적절한 시간에 메모리를 해제해야합니다. 예를 들면 다음과 같습니다.
- (void)someMethod
{
NSDate* date = [[NSDate alloc] init]; // date is __strong by default
NSLog(@"The date: %@", date); // date still contains the object created above
// Sometime before this point, the object date pointed to is released by the compiler
}
약한 참조는 하나 이상의 다른 강력한 참조가있는 동안에 만 객체를 유지합니다. 마지막으로 강력한 참조가 끊어 지자 객체는 컴파일러에 의해 해제되고 런타임에 의해 약한 객체 참조 (변수)는 nil
으로 변경됩니다. 위의 예와 같이 지역 변수에서 약한 변수를 거의 쓸모 없게 만듭니다. 예를 들어 :
- (void)someMethod
{
__weak NSDate* date = [[NSDate alloc] init]; // The date created is released before it's ever assigned to date
// because date is __weak and the newly created date has no
// other __strong references
NSLog(@"The date: %@", date); // This always prints (null) since date is __weak
}
가 로컬 범위에서 함께 작업 약한 강한 변수의 예를 보려면 (이 경우에만 엄격하게 제한 유용성을 것 정말 약한 변수 참조를 보여 만 여기에 표시됩니다) :
- (void)someMethod
{
NSDate* date = [[NSDate alloc] init]; // date stays around because it's __strong
__weak NSDate* weakDate = date;
// Here, the dates will be the same, the second pointer (the object) will be the same
// and will remain retained, and the first pointer (the object reference) will be different
NSLog(@"Date(%p/%p): %@", &date, date, date);
NSLog(@"Weak Date(%p/%p): %@", &weakDate, weakDate, weakDate);
// This breaks the strong link to the created object and the compiler will now
// free the memory. This will also make the runtime zero-out the weak variable
date = nil;
NSLog(@"Date: %@", date); // prints (null) as expected
NSLog(@"Weak Date: %@", weakDate); // also prints (null) since it was weak and there were no more strong references to the original object
}
두 번째 예제 코드에서 "날짜가 __weak이므로 항상이 (null)을 출력합니다"라는 질문에서 날짜는 0이지만 메모리 누수가 있습니까? 또는 할당이 취소 되었습니까? –
@RamyAlZuhouri 메모리 누수가 없습니다. 컴파일러는 새로 할당 된 날짜를 즉시 할당 취소하고 할당을 방해하지 않습니다 (이 경우). –
NSLog (@ "약한 날짜 : % @", 날짜); NSLog (@ "Weak Date : % @", weakDate)가 아니어야합니다. – NMunro