我想了解ARC的工作方式,而據我所知,應該是我錯在這裏做一些事情。這是我使用的代碼:的iOS ARC - 弱和強性能
接口:
@interface ViewController : UIViewController{
}
@property (strong, nonatomic) NSString * myString ;
@property (weak, nonatomic) NSString * myPointer ;
實現:
- (void)viewDidLoad{
[super viewDidLoad];
self.myString = @"Hello world!" ; // myString is strong
self.myPointer = self.myString ; // myPointer var is weak
[self performSelector:@selector(makeNilMyValue) withObject:nil afterDelay:1];
[self performSelector:@selector(printValues) withObject:nil afterDelay:2];
}
- (void) makeNilMyValue{
self.myString = nil ;
}
- (void) printValues{
NSLog(@"myString: %@", self.myString) ;
NSLog(@"myPointer: %@", self.myPointer) ;
}
執行此之後,我得到:
2012-02-26 11:40:41.652 test1[933:207] myString: (null)
2012-02-26 11:40:41.653 test1[933:207] myPointer: Hello world!
如果我沒有錯,因爲myPointer是軟弱,它不應該保留對象的內容。所以,它應該顯示爲零,而不是「世界,你好!」。
我在做什麼錯?
繼迦勒的答案,我創造了另一種弱指針,請參見下面的代碼:
- (void)viewDidLoad{
[super viewDidLoad];
self.myString = @"Hello world!" ; // myString is strong
self.myPointer = self.myString ; // myPointer var is weak
self.myPointer2 = self.myString ; // myPointer2 var is weak
[self performSelector:@selector(makeNilMyValue) withObject:nil afterDelay:1];
[self performSelector:@selector(printValues) withObject:nil afterDelay:2];
}
- (void) makeNilMyValue{
self.myPointer2 = @"value changed!" ;
self.myString = nil ;
}
- (void) printValues{
NSLog(@"myString: %@", self.myString) ;
NSLog(@"myPointer: %@", self.myPointer) ;
}
的一點是,我仍然有我曾經有過同樣的答案:
2012-02-26 12:08:13.426 test1[1333:207] myString: (null)
2012-02-26 12:08:13.427 test1[1333:207] myPointer: Hello world!
明智的答案,非常感謝。 – RGML 2012-02-26 12:40:34