在目标c中将字符串写入txt文件

时间:2013-05-10 16:54:04

标签: ios objective-c

拔出我的头发试图解决这个问题。我想读取和写一个数字列表到我的项目中的txt文件。但[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:& error]似乎没有向文件写入任何内容。我可以看到路径字符串返回一个文件路径,所以它似乎已找到它,但只是似乎没有写任何文件。

+(void)WriteProductIdToWishList:(NSNumber*)productId {

    for (NSString* s in [self GetProductsFromWishList]) {
        if([s isEqualToString:[productId stringValue]]) {
            //exists already
            return;
        }
    }

    NSString *string = [NSString stringWithFormat:@"%@:",productId];   // your string
    NSString *path = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"];
    NSError *error = nil;
    [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"%@", error.localizedFailureReason);


    // path to your .txt file
    // Open output file in append mode: 
}

编辑:路径显示为/var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt,确实存在。但请阅读:

NSString *path = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"];

只返回一个空字符串。

2 个答案:

答案 0 :(得分:10)

您正在尝试写入应用程序包内的位置,由于该包是只读的,因此无法修改该位置。您需要找到一个可写的位置(在您的应用程序的沙箱中),然后当您调用string:WriteToFile:时,您将获得所期望的行为。

应用程序通常会在第一次运行时从包中读取资源,将所述文件复制到合适的位置(尝试文档文件夹或临时文件夹),然后继续修改该文件。

因此,例如,沿着这些方向:

// Path for original file in bundle..
NSString *originalPath = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"];
NSURL *originalURL = [NSURL URLWithString:originalPath];

// Destination for file that is writeable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory];

NSString *fileNameComponent = [[originalPath pathComponents] lastObject];
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent];

// Copy file to new location
NSError *anError;
[[NSFileManager defaultManager] copyItemAtURL:originalURL
                                        toURL:destinationURL
                                        error:&anError];

// Now you can write to the file....
NSString *string = [NSString stringWithFormat:@"%@:", yourString]; 
NSError *writeError = nil;
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", writeError.localizedFailureReason);

继续前进(假设您希望随着时间的推移继续修改文件),您需要评估文件是否已存在于用户的文档文件夹中,确保在需要时仅从文件夹中复制文件(否则你每次都会用原始的包裹副本覆盖你修改过的文件。

答案 1 :(得分:2)

要逃避写入特定目录中文件的所有麻烦,请使用NSUserDefaults类来存储/检索键值对。这样,当你64岁的时候,你仍然会有头发。

相关问题