由于某些原因,在我的下面的代码中,replies
数组是NSLogging
正确的描述,但comment.replies
数组是NSLogging
null。
我立即假设这是由于我的代码中的内存管理问题,但我不相信这是真的。
请告诉我为什么会这样?
- (TBComment *) dictionaryToComment:(NSDictionary *)dict {
TBComment *comment = [[TBComment alloc] init];
[comment setBody:[dict objectForKey:@"body"]];
[comment setCommentID:[dict objectForKey:@"id"]];
[comment setCreated_at:[dict objectForKey:@"created_at"]];
[comment setUpdated_at:[dict objectForKey:@"updated_at"]];
[comment setUser:[self dictionaryToUser:[dict objectForKey:@"user"]]];
NSMutableArray *replies = nil;
if ([[dict allKeys] containsObject:@"replies"]) {
replies = [[NSMutableArray alloc] init];
for (NSDictionary *reply in [dict objectForKey:@"replies"]) {
NSLog(@"in");
[replies addObject:[self dictionaryToComment:reply]];
}
}
if (replies != nil) {
[comment setReplies:replies];
NSLog(@"COMMENT REPLIES = %@", comment.replies);
NSLog(@"REPLIES = %@", replies);
[replies release];
}
return [comment autorelease];
}
控制台 - >
2011-11-30 21:25:14.980 Timbrr[2379:f803] in
2011-11-30 21:25:14.980 Timbrr[2379:f803] COMMENT REPLIES = (null)
2011-11-30 21:25:14.980 Timbrr[2379:f803] REPLIES = (
"<TBComment: 0x68dbeb0>"
)
- (void) setReplies:(NSArray *)_replies {
hasReplies = (_replies == nil ? NO : ([_replies count] == 0 ? NO : YES));
//replies is synthesised
}
答案 0 :(得分:7)
在看到setReplies:
的实施后,我认为你并不完全理解@synthesize
的工作原理。
@synthesize replies;
将为此实例变量生成一个getter和一个setter。 但是,因为你要覆盖它(并且不正确),合成的setter被抛到一边。 (事实上,根本没有为你创建一个setter,因为你自己写了一个。)
根本问题是,在setReplies:
的实现中,您实际上并未将replies
实例变量的值分配给setter的参数。
我认为你想要的是:
- (void) setReplies:(NSArray *)_replies {
hasReplies = (_replies == nil ? NO : ([_replies count] == 0 ? NO : YES));
// How is your ivar defined in the header file? As _replies, or replies?
if (replies != _replies) {
[replies release];
replies = [_replies retain];
}
}
答案 1 :(得分:3)
我怀疑comment
是nil
(虽然这需要明确的nil
- 在TBComment
中返回代码,这是可能的,但不常见),或者-replies
或-setReplies:
未正确实施。你有那些自定义实现吗?
setReplies:
的实施从未设置_replies
。
答案 2 :(得分:0)
永远不会设置replies
属性 - 当您定义setReplies:
时,@synthesize
指令不会创建任何setter方法。