I would like to know how weak property work in Objective-C. In this example the value of the weak property "myString" in "myClass" is kept only when I print it with NSLog. Why is that?
#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;
}
If the NSLog-line in the readString-method is commented out myInstance.myString becomes "(null)". Why??