客观C变量可通过多种方法访问
这是我在ObjectiveC中的第二天编程,所以我为noob问题表示歉意。客观C变量可通过多种方法访问
我有一个视图控制器使用异步和asihttprequest,做一个API调用:
@synthesize loadingStatus;
- (void)loadStatsData
{
[indicator setHidden:NO];
loadingStatus = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"bad", nil] forKeys:[NSArray arrayWithObjects:@"amount", nil ] ];
[RESTApiController request:@"/method.json" method:@"GET" options:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObject:@"amount"] forKeys:[NSArray arrayWithObject:@"receiving"] ] parent:self];
}
和接收这样的:
应用崩溃时它会尝试使用loadingStatus变量在requestFinished()。我想不知怎么变量被取消了,但我不确定如何解决这个问题。
两个问题: 1)我怎样才能保持loadingStatus的状态跨越方法的调用,所以我可以在我写的代码 2的方式来使用它)有没有达到我的检查目标的更好的方法,如果API调用完成并隐藏ActivityIndicator?
-M。
做这种方式:指loadingStatus作为self.loadingStatus
self.loadingStatus = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"bad", nil] forKeys:[NSArray arrayWithObjects:@"amount", nil ] ];
这样的话,它会通过访问,并做了就可以了(在.h文件中的部分@property)保留。
另外,编程提示:将行分成更小的语句,以便更易于调试。
但是,只有当属性被声明为'(retain)'时。 – 2011-05-10 23:26:09
@Squeegy - 很对。谢谢。 – Rayfleck 2011-05-10 23:27:11
你是对的,loadingStatus正在被释放。这是因为价值正在自动释放。
如果更改
loadingStatus = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"bad", nil] forKeys:[NSArray arrayWithObjects:@"amount", nil ] ];
到
loadingStatus = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"bad", nil] forKeys:[NSArray arrayWithObjects:@"amount", nil ] ];
[loadingStatus retain];
或
loadingStatus = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"bad", nil] forKeys:[NSArray arrayWithObjects:@"amount", nil ] ];
那么你的代码将工作。
原因是从dictionaryWithObjects:forKeys返回的对象已经对它调用了autorelease,因此如果要避免它被释放,则需要调用retain。
作为参考,如果调用alloc/init,将得到一个保留计数为1的对象。如果使用诸如dictionaryWithObjects:forKeys之类的方法:将得到一个保留计数为0的对象。要解决这个问题,只需添加一个保留,你就会很好。
苹果有一些非常好的内存管理文档。我建议检查出来,当你有机会
希望这有助于!
-Scott
你会得到什么错误? – 2011-05-10 23:14:18