我正在尝试创建我的计算的一个plist但事实证明列表是空的....请帮助这里是我的code.is有任何其他方法将字符串写入除此之外的文件... < / p>
-(float)calculate
{
if(!self.operatorLabel.text.length)
return self.operand2;
float result=0;
switch([self.operatorLabel.text characterAtIndex:0])
{
case '+':result=self.self.operand1+self.operand2;
break;
case '-':result=self.operand1-self.operand2;
break;
case '*':result=self.operand1*self.operand2;
break;
case '/':if(self.operand2==0)
divideByZeroFlag=true;
else
result=self.operand1/self.operand2;
break;
default:self.operand1=0;
result=self.operand2;
break;
}
if(!divideByZeroFlag&&self.operand1!=0)
{
NSString *data=[NSString stringWithFormat:@"%g%@%g=%g",self.operand1,self.operatorLabel.text,self.operand2,result];
NSMutableDictionary *dat;
[dat setObject:data forKey:@"nthing"];
[dat writeToFile:@"memory.plist" atomically:YES];
}
return result;
}
答案 0 :(得分:1)
1 - 您必须初始化dat。
2 - [NSDictionary writeToFile]期望完整路径,而不仅仅是名称。
修改强>
要创建路径,请执行以下操作:
+ (NSString*) createFullFilePath:(NSString *)fileName
{
//Look at documents for existing file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]];
NSFileManager* fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:path])
{
NSError *error;
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
if (error)
NSLog (@"%@", [error localizedDescription]);
}
return path;
}
完成后,使用以下代码写入该路径(请注意,这也会初始化字典(检查NSLogs以查看您正在执行的操作会产生结果):
NSString * path = [self createFullFilePath:@"memory.plist"];
NSLog (@"@%", path);
NSMutableDictionary *dat = [NSMutableDictionary dictionary];
NSLog (@"@%", dat);
[dat setObject:data forKey:@"nthing"];
[dat writeToFile:path atomically:YES];
答案 1 :(得分:0)
为什么是plist文件? plist很适合数组和字典,但我认为没有理由在plist中存储一个简单的字符串。
怎么样......
NSString *data = ...
NSError *error = nil;
[data writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];