2012-11-22 33 views
0

C族人,我是一个刚刚跳入Obj-C数天的新手。我有这个问题,我知道也许这是一个没有道理但我花了很多时间在网上搜索,但无法找到相关答案,请在这里帮助。Objective-C NSString在循环后变为空

我想写一个简单的n元树数据结构只是为了实践。我创建了一个名为ICNode的类,其中它为其子级,父级和深度保存了一个NSMutableArray。

#import <Foundation/Foundation.h> 

@interface ICNode : NSObject 
{ 

} 
@property (nonatomic, weak) id content; 
@property (nonatomic, weak) ICNode *parent; 
@property (nonatomic, strong) NSMutableArray *children;  // should store ICNode 
@property (nonatomic) int depth; // root is 0, not set is -1 

然后我写了一个简单的测试代码来测试它。

for (int i = 1; i <= 2; i++) { 
    NSString *string = [[NSString alloc] initWithFormat:@"Test %d", i]; 
    ICNode *child = [[ICNode alloc] init]; 
    [child setContent:string]; 
    [root addChild:child]; 
    STAssertEqualObjects([child parent], root, @"child's parent is root"); 
    STAssertEquals([child depth], 1, @"children's depth is 1"); 
} 
STAssertEquals([root numberOfChildren], 2, @"root's number of children is testRun"); 
NSLog(@"%@", root); 

我在这里的问题是,在代码的最后一行时,NSLog的,我希望看到这样的事情:

"Content: Test 1(depth=1) -> Parent: I am Root -> Children: (null)", 
"Content: Test 2(depth=1) -> Parent: I am Root -> Children: (null)" 

而是它始终是

"Content: (null)(depth=1) -> Parent: I am Root -> Children: (null)", 
"Content: (null)(depth=1) -> Parent: I am Root -> Children: (null)" 

我然后在那里放置一个断点,并发现在addChild方法之后,它是find,但是在循环结束后,子元素的内容将变为null。我不太熟悉指针的东西,所以我怀疑这是与指针有关的东西。

另一种看法是,如果我做这样的事情,

NSString *string = [[NSString alloc] initWithFormat:@"Test %d", 1]; 
ICNode *child = [[ICNode alloc] initWithContent:string parent:root]; 
NSString *string1 = [[NSString alloc] initWithFormat:@"Test %d", 2]; 
ICNode *child1 = [[ICNode alloc] initWithContent:string1 parent:root]; 
NSLog(@"%@", [root description]); 

然后输出是罚款。但我确实希望能够使用循环创建节点。

请帮忙,谢谢。

+0

查找“弱”是什么意思。 (变量“字符串”已经超出了上下文。) –

回答

1

由于ICNode的parentcontent属性为,只要最后一个强参考消失,它们就会变为零。

在代码片段中,您从本地变量string设置了content,并且该变量对于for循环是本地的。如果你将它移到for循环的外部,它将进入函数ICNode的主体content属性不会成为零。

但是,很可能要content成为强,复制属性,而不是