1
votes

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??

1

1 Answers

1
votes

From Apple:

weak Specifies that there is a weak (non-owning) relationship to the destination object. If the destination object is deallocated, the property value is automatically set to nil.

So Basically when arc insert code into [readString], he does:

NSString *tempString = [[NSString alloc] initWithUTF8String:buffer];
    myString = tempString;
// + arc [tempString release]

So your tempString no longer exist outside the method, because nothing retain it.

But when you add NSlog inside [readString] with myString, NSLog will keep reference to the pointer (i don't know exactly how), but he actually does since he logs them.