我想知道弱属性在 Objective-C 中是如何工作的。在此示例中,“myClass”中的弱属性“myString”的值仅在我使用 NSLog 打印时才保留。这是为什么?
#import <Foundation/Foundation.h>
#include <stdio.h>
@interface myClass : NSObject
@property (nonatomic, weak)NSString *myString;
- (void)readString;
@end
@implementation myClass
@synthesize myString;
- (void)readString
{
const int MAXBUFFER = 80;
char buffer[MAXBUFFER+1];
NSLog(@"Input string:");
fgets(buffer, MAXBUFFER, stdin);
NSString *tempString = [[NSString alloc] initWithUTF8String:buffer];
myString = tempString;
NSLog(@"myString: %@", myString); // Why does this line make all the difference?
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
myClass *myInstance = [[myClass alloc] init];
[myInstance readString];
NSLog(@"myInstance.myString: %@", myInstance.myString);
}
return 0;
}
如果 readString 方法中的 NSLog 行被注释掉,myInstance.myString 变为“(null)”。为什么??