将数组内容写入文件

时间:2013-01-14 23:57:13

标签: ios objective-c nsarray

我整天都在努力使用这里的答案,但我找不到适合我的解决方案,所以我想我会寻求帮助:

我有一个从实体中提取的对象数组。

我想要做的就是将对象写入文件。

到目前为止,我想出的是:

    NSLog(@" Exported Records: %i", [exportArray count]); 
    // the count here is 4 records.
    //Each record has about 8 elements. 
//I'm just trying to get this working with the first two elements right now

        NSString *writeString = nil;
        NSError *error = nil;
        int i = 0;
        NSString *key = nil;
        NSString *tempString = nil;
        for (i=0; i<[exportArray count]; i++)
        {
            tempString = [tempString stringByAppendingString: @" \n "];

            for (int j=0; j<3; j++)
            {
                if (j == 0)
                {
                    key = [[exportArray objectAtIndex:i]  valueForKey:@"title"];
                    //[NSString stringWithFormat:tempString2, [[exportArray objectAtIndex:i]  valueForKey:@"title"]];
                }
                if (j == 1)
                {
                    key = [[exportArray objectAtIndex:i]  valueForKey:@"username"];
                    //[NSString stringWithFormat:tempString2, [[exportArray objectAtIndex:i]  valueForKey:@"username"]];
                }
                writeString = [NSString stringWithFormat:tempString, key];
            }
        }

        // Write to the file
        [writeString writeToFile:dataFile atomically:YES
                    encoding:NSUTF8StringEncoding error:&error];
        if (error)
        {
            NSLog(@"%@", error);
        }

现在,我得到的是最后一项,所以我要覆盖字符串。但是,必须有一个更好的方法来实现这一目标。如果这里有另一个答案符合我的问题,请告诉我,或者请发表一些想法。

更新

当我记录exportArray时,我得到了这个:

"<ItemEntity: 0x1ddf6560> (entity: ItemEntity; id: 0x1ddf46d0 <x-coredata://78FBC4A5-AE1A-4344-98AB-978126457D96/ItemEntity/p2> ; data: <fault>)",
    "<ItemEntity: 0x1ddf6800> (entity: ItemEntity; id: 0x1ddf46e0 <x-coredata://78FBC4A5-AE1A-4344-98AB-978126457D96/ItemEntity/p2051> ; data: <fault>)",
    "<ItemEntity: 0x1ddf6860> (entity: ItemEntity; id: 0x1ddf45d0 <x-coredata://78FBC4A5-AE1A-4344-98AB-978126457D96/ItemEntity/p3075> ; data: <fault>)",
    "<ItemEntity: 0x1ddf68c0> (entity: ItemEntity; id: 0x1ddf45e0 <x-coredata://78FBC4A5-AE1A-4344-98AB-978126457D96/ItemEntity/p5124> ; data: <fault>)"
)

当我记录实际值时:

NSLog(@" Exported titles: %@", [exportArray valueForKey:@"title"]);
NSLog(@" Exported usernames: %@", [exportArray valueForKey:@"username"]);

我得到了正确的结果。我只是不知道如何将这些和其他属性联系在一起..

  Exported titles: (
    1,
    2,
    4,
    6
)
  Exported usernames: (
    ellis,
    david,
    bea,
    ian
)

5 个答案:

答案 0 :(得分:8)

如果您的数组中只有NSDictionaries,则可以使用writeToFile:atomically:来保存.plist格式的文件(比CSV更容易阅读)。

查看Apple Docs for NSArray,并在plists上写好。

所以你最终会得到:

[exportArray writeToFile:fileName atomically:YES];

编辑:您无法将核心数据对象保存到文件中。所以你要做的是创建一个只包含你想要的数据的临时数组,然后将其写入文件。

NSMutableArray* arrayToSave = [NSMutableArray arrayWithCapacity:exportArray.count];
[exportArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary* exportDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                [obj objectForKey:@"username"], @"username",
                                [obj objectForKey:@"title"], @"title", nil];
    [arrayToSave addObject:exportDict];
}];

[arrayToSave writeToFile:fileName atomically:YES];

答案 1 :(得分:7)

使用此,

[exportArray writeToFile:dataFile atomically:YES];

NSArray使用方法writeToFile:来执行此操作。检查the documentation here.如果阵列中没有自定义对象,则此方法可以正常工作。

如果您只想保存标题或用户名(即使它在数组中有自定义对象),您可以这样做:

NSArray *array1 = [exportArray valueForKey:@"title"];
[array1 writeToFile:dataFile atomically:YES];

NSArray *array2 = [exportArray valueForKey:@"username"];
[array2 writeToFile:dataFile atomically:YES];

答案 2 :(得分:4)

[exportArray writeToFile: dataFile atomically:YES];

创建并写入.plist文件格式。

除非数组中的对象不受plist支持。

支持的对象包括:属性列表对象`NSStringNSNumberNSDateNSDataNSArrayNSDictionary

plist格式不支持

UItextFieldUItextView,因此不起作用。如果您要保存的只是来自它们的文本,请将文本放在数组中。

答案 3 :(得分:2)

试试这个:


    NSMutableString *string = [NSMutableString string];
    for (NSDictionary* dict in exportArray) {
        for (NSString* key in [dict allKeys]) {
            NSObject* value = [dict objectForKey:key];
            [string appendFormat:@"%@ = %@\n", key, value];
        }
    }

    // Write to the file
    NSError* error = nil;
    [string writeToFile:dataFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error)
        NSLog(@"%@", error);

答案 4 :(得分:2)

我会考虑首先将其转换为NSData,然后将其保存为二进制plist而不是人类可读的plist,因为二进制plist读取速度要快得多(2-3x我相信但我不记得哪个WWDC视频了解释了)。为此,首先需要将NSArray转换为NSData对象:

(资料来源:Rob Napier's answer to this SO question

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
// "Note that all the objects in array must conform to the NSCoding protocol."

NSString *error;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:array
format:NSPropertyListBinaryFormat_v1_0 options:NULL error:&error];

然后您可以使用以下命令将NSData写入文件:

[data writeToFile:path atomically:YorN];

要阅读它,请使用:

NSData *rawdata = [[NSData alloc] initWithContentsOfFile:/*file*/];
NSData *arrayData = [NSPropertyListSerialization propertyListWithData:rawdata
options:NULL format:NULL error:&error];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];

你真的只需要对非常大的.plist文件使用二进制进程,但它很方便了解。

相关问题