我正在尝试构建一棵树来存储 USB 设备信息。我以为我会使用 NSMutableArray 和 NSMutableDictionary 来包含这些信息。我的问题是我从来没有学过软件工程——我边走边学——而且我对树理论一无所知。
我的树基于 USB 位置 ID,它有 8 个半字节长。据我了解,每个半字节代表树的一层(如果您明白我的意思)。我已经编写了一些测试代码,看看我是否可以正确地构建我的树 - 遗憾的是,我似乎做不到!
#import <Foundation/Foundation.h>
#define MAXCHILDREN 0xf
NSDictionary* AddItemToTree(NSDictionary* nodeEntry, unsigned int value, int depth)
{
// Convert the value into a set of nibbles
char *bytes = (char *)&value;
char byte = bytes[depth];
NSMutableDictionary* thisEntry = [[[NSMutableDictionary alloc] initWithDictionary:nodeEntry] autorelease];
if (byte == 0)
{
[thisEntry setObject:[NSString stringWithFormat:@"%08x",value] forKey:@"Value"];
[thisEntry setObject:[NSString stringWithFormat:@"%08x",byte] forKey:@"Byte"];
[thisEntry setObject:[NSNumber numberWithInt:depth] forKey:@"Depth"];
return thisEntry;
}
if(![[thisEntry allKeys]containsObject:@"ChildEntries"])
{
NSMutableArray* childArray = [[NSMutableArray alloc]init];
NSMutableDictionary* newNode = [[NSMutableDictionary alloc] init];
[childArray addObject:AddItemToTree(newNode,value,++depth)];
[thisEntry setObject:[NSNumber numberWithInt:depth] forKey:@"Depth"];
[thisEntry setObject:[NSString stringWithFormat:@"%08x",value] forKey:@"Value"];
[thisEntry setObject:[NSString stringWithFormat:@"%08x",byte] forKey:@"Byte"];
[thisEntry setObject:childArray forKey:@"ChildEntries"];
[newNode release];
[childArray release];
}
else
{
[[thisEntry objectForKey:@"ChildEntries"]addObject:AddItemToTree(thisEntry,value, ++depth)];
}
return thisEntry;
}
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableDictionary* treenode=[[NSMutableDictionary alloc]init];
char bytearray[4] = {0x0F, 0x0F, 0x02, 0x00};
unsigned int *value = (unsigned int*)bytearray;
char bytearray2[4] = {0x0F, 0x02, 0x00, 0x00};
unsigned int *value2 = (unsigned int*)bytearray2;
char bytearray3[4] = {0x0F, 0x02, 0x00, 0x00};
unsigned int *value3 = (unsigned int*)bytearray3;
[treenode setObject:[NSNumber numberWithInt:0] forKey:@"Depth"];
[treenode setObject:[NSString stringWithFormat:@"%08x",*value] forKey:@"Value"];
[treenode setObject:AddItemToTree(treenode,*value, 0) forKey:@"ChildEntries"];
// [[treenode objectForKey:@"ChildEntries"]addObject:AddItemToTree(treenode,*value2, 0)];
[treenode writeToFile:@"/Users/headbanger/Desktop/test.plist" atomically:YES];
[pool release];
}
添加一个 USB 位置 ID 效果很好。添加第二个(通过取消注释 main 中的行)会导致 SIGABRT。我确信这非常简单,而且我犯了一个典型的新手错误。但是,这对我来说并不明显,您可以提供的任何帮助都将非常受欢迎。
我的树需要看起来像这样:
F-
|--F-
| |--2
|
|--2
即使尝试添加第三个字节数组,这棵树也应该是真的。
如果您可以在不针对 USB 的情况下回答问题,那将是最有帮助的,因为我真的很想了解树木以及我做错了什么。也就是说,如果有一种快速简便的方法可以在 Objective-C 中为我构建一棵树,那么我很想听听。
所以请专家们,有人能告诉我我做错了什么吗?感谢您的时间。