Objective-C,在NSLog输出后保留变量

时间:2022-12-01 22:53:16

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?

我想知道Objective-C中的弱属性是如何工作的。在此示例中,仅当我使用NSLog打印时,“myClass”中的弱属性“myString”的值才会保留。这是为什么?

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

如果readString方法中的NSLog-line被注释掉,myInstance.myString将变为“(null)”。为什么??

1 个解决方案

#1


1  

From Apple:

来自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.

weak指定与目标对象存在弱(非拥有)关系。如果取消分配目标对象,则属性值将自动设置为nil。

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

所以基本上当将弧插入[readString]时,他会:

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

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

所以你的tempString不再存在于方法之外,因为没有任何东西保留它。

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.

但是当你使用myString在[readString]中添加NSlog时,NSLog将继续引用指针(我不确切知道如何),但实际上他确实记录了它们。

#1


1  

From Apple:

来自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.

weak指定与目标对象存在弱(非拥有)关系。如果取消分配目标对象,则属性值将自动设置为nil。

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

所以基本上当将弧插入[readString]时,他会:

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

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

所以你的tempString不再存在于方法之外,因为没有任何东西保留它。

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.

但是当你使用myString在[readString]中添加NSlog时,NSLog将继续引用指针(我不确切知道如何),但实际上他确实记录了它们。