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

use*_*723 2 objective-c ios

拉出我的头发试图解决这个问题.我想读取和写一个数字列表到我的项目中的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: 
}
Run Code Online (Sandbox Code Playgroud)

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

NSString *path = [[NSBundle mainBundle] pathForResource:@"WishList" ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)

只返回一个空字符串.

isa*_*aac 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);
Run Code Online (Sandbox Code Playgroud)

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