无法以编程方式修改文件objective-c

时间:2016-05-03 13:54:36

标签: ios file nsfilemanager nsmutabledata

我正在尝试重写一个文件,从中我可以获取数据。但我得到一个错误,表示我无权更改或删除。

我在这里获取数据:

- (id) init {
if (self = [super init]) {
    NSError *error = nil;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"slot_reader_source" ofType:@"txt"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    data = [NSMutableData dataWithContentsOfFile:filePath];
    allData = [[NSMutableDictionary alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData:data
                                                                                              options:kNilOptions
                                                                                                error:&error]];
}
return self;
}

我在这里尝试更改该文件

- (void) addNewWord: (NSString *) word {
NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
NSArray *alphabet = [[allData objectForKey:@"words"] objectForKey:[NSString stringWithFormat:@"%@%d", [[NSUserDefaults standardUserDefaults] objectForKey:@"language"], 1]];
NSMutableString *aphabetString = [[NSMutableString alloc] initWithCapacity:1];
for (NSString *letter in alphabet) {
    [aphabetString appendString:letter];
}
NSCharacterSet *allowedSymbols = [NSCharacterSet characterSetWithCharactersInString:aphabetString];
word = [[[word componentsSeparatedByCharactersInSet:allowedSymbols] componentsJoinedByString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];

NSInteger size = [word length];
NSMutableArray *thisSizeLangWordsBuffer = [[NSMutableArray alloc] initWithArray:[[allData objectForKey:@"words"] objectForKey:[NSString stringWithFormat:@"%@%d", language, size]]];
[thisSizeLangWordsBuffer addObject:word];
NSMutableDictionary *newData = [[NSMutableDictionary alloc] initWithDictionary:[allData objectForKey:@"words"]];

[newData setObject:thisSizeLangWordsBuffer forKey:[NSString stringWithFormat:@"%@%d", [[NSUserDefaults standardUserDefaults] objectForKey:@"language"], size]];
NSMutableDictionary *newAllData = [[NSMutableDictionary alloc] initWithDictionary:allData];
[newAllData setObject:newData forKey:@"words"];
//allData = nil;
[allData setDictionary:newAllData];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"slot_reader_source" ofType:@"txt"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSError* error = nil;
data = [NSMutableData dataWithData:[NSJSONSerialization dataWithJSONObject:newAllData options:NSJSONWritingPrettyPrinted error:nil]];
[[NSFileManager defaultManager] removeItemAtURL:url error:&error];
BOOL res = [data writeToFile:filePath options:NSDataWritingAtomic error: &error];
NSString *newText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}

0 个答案:

没有答案