Objective-C省市区用树节点来存储和读取

来源:互联网 发布:跑酷教程软件 编辑:程序博客网 时间:2024/05/21 06:44

文档请到http://wenku.baidu.com/view/234bb67b52ea551810a687ce下载

main.m
#import <Foundation/Foundation.h>#import "TreeNode.h"int main(int argc, const char * argv[]) {    //准备工作    NSString * file = @"/Users/henry/Desktop/2.27/2.27/area副本.txt";    NSString * buffer = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];    NSCharacterSet * cSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789 "];    NSArray * array = [buffer componentsSeparatedByString:@"\n"];    TreeNode * country = [TreeNode treeNodeWithNode:@"China"];        //存储    for (NSString * str in array) {        if (![str hasPrefix:@"  "]) {            NSString * s1 = [str stringByTrimmingCharactersInSet:cSet];            TreeNode * province = [TreeNode treeNodeWithNode:s1];            [country.subnode addObject:province];        }        if ([str hasPrefix:@"  "] && ![str hasPrefix:@"    "]) {            NSString * s2 = [str stringByTrimmingCharactersInSet:cSet];            TreeNode * city = [TreeNode treeNodeWithNode:s2];            TreeNode * province = [country.subnode lastObject];            [province.subnode addObject:city];        }        if ([str hasPrefix:@"    "]) {            NSString * s3 = [str stringByTrimmingCharactersInSet:cSet];            TreeNode * district = [TreeNode treeNodeWithNode:s3];            TreeNode * procince = [country.subnode lastObject];            TreeNode * city = [procince.subnode lastObject];            [city.subnode addObject:district];        }    }        //输出    for (TreeNode * province in country.subnode) {        if ([province.node isEqualToString:@"上海"]) {            for (TreeNode * city in province.subnode) {                if ([city.node isEqualToString:@"上海"]) {                    for (TreeNode * district in city.subnode) {                        NSLog(@"%@", district.node);                    }                }            }        }    }    return 0;}
TreeNode.h
#import <Foundation/Foundation.h>@interface TreeNode : NSObject@property(nonatomic, retain)NSString * node;@property(nonatomic, retain)NSMutableArray * subnode;- (id)initWithNode:(NSString *)node;+ (id)treeNodeWithNode:(NSString *)node;- (void)dealloc;@end
TreeNode.m
#import "TreeNode.h"@implementation TreeNode- (id)initWithNode:(NSString *)node {    self = [super init];    if (self) {        [self setNode:node];        [self setSubnode:[NSMutableArray array]];    }    return self;}+ (id)treeNodeWithNode:(NSString *)node {    TreeNode * treenode = [[TreeNode alloc] initWithNode:node];    return [treenode autorelease];}- (void)dealloc {    [_node release];    [_subnode release];    [super dealloc];}@end<span style="color:#ff0000;"></span>


0 0
原创粉丝点击