gpt4 book ai didi

iphone - iOS保留,分配

转载 作者:行者123 更新时间:2023-12-01 17:19:31 27 4
gpt4 key购买 nike

我观察到以下行为。

接受了两个属性变量。

@property (nonatomic, retain) NSString *stringOne;
@property (nonatomic, assign) NSString *stringTwo;

在.m文件下面的代码中编写。
 NSMutableString *localstring= [[NSMutableString alloc] initWithString:@"test"];
self.stringOne = localstring;
NSLog(@"localstring = %d", [string retainCount]);
NSLog(@"string one retain count = %d", [self.stringOne retainCount]);
self.stringTwo = localstring;
NSLog(@"localstring = %d", [localstring retainCount]);
NSLog(@"string two retain count = %d", [self.stringTwo retainCount]);

在这里,由于分配,localstring保留计数为1。现在我给
self.stringOne = localString。

由于stringOne的keep属性,localstring的保留计数将变为2。现在我给
self.stringTwo = localString。

即使在这里,本地字符串保留计数也增加一。注意,我已经为stringTwo赋予了assign属性。实际上,localstring或stringTwo的保留计数不应为1,因为它是assign属性。
如果我错了,请纠正我。

谢谢
吉森

最佳答案

转储retainCount;这是没有用的。 http://www.whentouseretaincount.com/

困惑的根源在于不了解指针的工作方式。像这样修改您的代码:

@interface BBQ:NSObject
@property (nonatomic, retain) NSString *stringOne;
@property (nonatomic, assign) NSString *stringTwo;
@end

@implementation BBQ
- (void) burn
{
NSMutableString *localstring= [[NSMutableString alloc] initWithString:@"test"];
self.stringOne = localstring;
NSLog(@"localstring = %p", localstring);
NSLog(@"string one = %p", self.stringOne);
self.stringTwo = localstring;
NSLog(@"localstring = %p", localstring);
NSLog(@"string two = %p", self.stringTwo);
}
@end

它会喷出这样的东西:
2013-04-11 08:48:13.770 asdffadsfasddfsa[18096:303] localstring = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] string one = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] localstring = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] string two = 0x10010aaf0

播放中只有一个字符串实例。 localstringstringOnestringTwo都完全包含对NSMUtableString的一个实例的引用。

因此,您会看到 alloc的一个字符串实例的+1 RC,给 stringOne属性的分配的+1,而 stringTwo没有变化。

(RC仅应以增量为依据进行推理;如果保留一个对象,则在不再需要该对象时需要将其与发行版之间进行平衡。该对象可能被其他对象保留是无关紧要的。)

关于iphone - iOS保留,分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15942034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com