xcode – 将数组保存到plist

我正在尝试将一些项目存储到pList中.这是数组循环:

for (id obj in items)
NSLog(@"obj: %@",obj);

输出NSLog:

2013-03-27 13:00:40.072 mycode[47436:c07] obj: Red
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Blue
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Green

// arrayWithObjects有效.但我不知道如何(循环?)通过我的项目保存到plist文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        Nsstring *documentsDirectory = [paths objectAtIndex:0];
        Nsstring *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];


    NSFileManager *filemgr;
    filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: path]) {
        NSLog(@"%@",path);

    NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutablecopy];
    NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
    newArray = [NSArray arrayWithObjects:@"Red",@"Green",@"Blue" nil]; // <--- WORKS!
    newArray = [NSArray arrayWithObjects:items,nil]; // <-- ? 
    [plist setobject:newArray forKey:@"Hi"];
    [plist writetoFile:path atomically:YES];
    [plist release];


    } else {
        NSLog(@"File not found");
    }

    [filemgr release];

解决方法

也许这段代码可以帮助你.

NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];

newArray = [NSArray arrayWithObjects:@"Red",@"Blue" nil];
for(int i=0;i<newArray.count;i++)
{
 [targetArray addobject:[newArray objectAtIndex:i]];

}
[plist setobject:targetArray forKey:@"Hi"];
[plist writetoFile:path atomically:YES];

或另一种方法

NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];

for (id obj in items)
{
 [targetArray addobject:items];
 }
[plist setobject:targetArray forKey:@"Hi"];
[plist writetoFile:path atomically:YES];

希望这可以帮助 !!!

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...