我试图了解 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 很弱,它不应该保留对象的内容。因此,它应该显示 nil 而不是“Hello World!”。
我究竟做错了什么?
根据 Caleb 的回答,我创建了另一个弱指针,请参见下面的代码:
- (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!