gpt4 book ai didi

iphone - @property 中的内存损坏

转载 作者:行者123 更新时间:2023-11-28 18:07:15 26 4
gpt4 key购买 nike

我有下一段代码,一个具有此属性的 iVar 保留并在它的类 dealloc 方法中释放。 iVar 用于 2 种方法并不断更改值,但有时,当我使用该值时,该值已损坏。这是为什么?

.h

@interface ChatController : NSObject <ASIHTTPRequestDelegate>{
NSTimer *timer;
NSString *_idLastMessageFromServer;
}

@property(nonatomic, retain)NSString *idLastMessageFromServer;
@end

.m

@implementation ChatController

@synthesize idLastMessageFromServer = _idLastMessageFromServer;

- (void)initLoopTimer{
timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(update:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)update:(id)sender{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:CONSTANT_YYYY];
[request setDelegate:self];
[request addPostValue:_idLastMessageFromServer forKey:CONSTANT_XXX];
[request setDidFinishSelector:@selector(requestUpdateFinish:)];
[request startAsynchronous];
}

- (void)requestUpdateFinish:(ASIHTTPRequest *)request{
NSString *response = [request responseString];
if(response && response.length){
if(![response isEqualToString:CHAT_RESPONSE_NO_MESSAGES]){
NSArray *array = [response componentsSeparatedByString:CHAT_PARSE_RESPONSE];
if(array && [array count] == 2){
**_idLastMessageFromServer = [array objectAtIndex:0];**
}
}
}
}

但是当循环调用方法update:时,就在这行代码中崩溃了

[request addPostValue:_idLastMessageFromServer forKey:CONSTANT_XXX];

带有 EXC_BAD_ACCESS 消息,但为什么呢?

最佳答案

这一行:

_idLastMessageFromServer = [array objectAtIndex:0];

应该是

self.idLastMessageFromServer = [array objectAtIndex:0];

这将直接访问属性而不是变量,从而在赋值期间触发保留/释放。否则,指针被赋值,但从数组中取出的对象并没有被保留,它可能很快就会失效,剩下一个指向已释放对象的指针。

关于iphone - @property 中的内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10483808/

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