0

我需要能够将 NSMutableArray 给定数据的表格视图的内容保存到 txt 文件中,然后需要在包含表格视图的窗口时自动重新打开该文件。我正在为 mac 制作应用程序,
谢谢这是数据源的代码:

#import "tableViewData.h"
#import "Customer.h"
@implementation tableViewData
-(id) init
{
self = [super init];
if (self) {
    list = nil;
    filepath = @"/Users/Gautambir/Desktop/CustomerNames.txt";
    if ([[NSFileManager defaultManager]fileExistsAtPath:filepath]) {
        list = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
    }
    else
    list = [[NSMutableArray alloc]initWithObjects:name,memberNumber ,nil];
        [list writeToFile:filepath atomically:YES];
}
return self;
}

-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
return [list count];
}

-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn     *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [Customer valueForKey:identifier];
}

-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
}


-(void)save{
[list writeToFile:filepath atomically:YES];
}
-(IBAction)add:(id)sender{
[list addObject:[[Customer alloc]init]];
[tableView reloadData];

NSLog (@"array:%@",list);


}

-(IBAction)remove:(id)sender{
NSInteger row = [tableView selectedRow];
if (row != -1) {
    [list removeObjectAtIndex:row];
}

[tableView reloadData];

}




-(void)dealloc
{
[super dealloc];
}


@end

这是客户对象类的 .m 文件:

#import "Customer.h"

@implementation Customer

@synthesize name;
@synthesize memberNumber;


-(id) init
{
self = [super init];
if(self) {
    name = @"Test";
    int i = arc4random()%1000000000000000000;
    if (i<0) {
        memberNumber = i*-1;
    }
    else
        memberNumber = i;
}
return self;

}

-(void)dealloc
{
[name release];
[super dealloc];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
    name = [[aDecoder decodeObjectForKey:@"name"]retain];
    memberNumber = [aDecoder decodeIntForKey:@"memberNumeber"];
}
return self;

}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:@"name"];
[aCoder encodeInt:memberNumber forKey:@"memberNumber"];
}

@end

强文本

4

1 回答 1

0

很抱歉发布另一个答案 - 我误读了标签,我的第一个答案是依赖 iOS。这是在 OSX 中执行此操作的方法:

保存

NSMutableArray *array = ...  //your array

[array addObject:...]; 
[array addObject:...];
[array addObject:...];
...

// then use an NSData to store the array
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSString *path = @"/Users/User/path...";
[data writeToFile:path options:NSDataWritingAtomic error:nil];

检索

NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

塞巴斯蒂安

于 2012-04-10T22:08:00.603 回答