-1

嗨,我正在尝试创建我的计算的 plist,但结果列表是空的....请帮助这里是我的代码。除了这个之外,还有其他方法可以将字符串写入文件...

-(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;
}
4

2 回答 2

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];
于 2013-08-13T05:18:28.450 回答
0

为什么是 plist 文件?plist 非常适合数组和字典,但我认为没有理由将简单的字符串存储在 plist 中。

怎么样...

NSString *data = ...
NSError *error = nil;
[data writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
于 2013-08-13T05:18:47.260 回答