質問

hi am trying to create a plist of my calculations but it turns out the list is empty....pls help here is my code.is there any othe way to write strings to a file other than this...

-(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;
}
役に立ちましたか?

解決

1 - You must initialize dat.

2 - [NSDictionary writeToFile] expects full path, not just the name.

EDIT:

To create a path, do this:

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

Once done, write to that path using following code (note that this initializes dictionary too (check NSLogs to see what you are doing yields results):

NSString * path = [self createFullFilePath:@"memory.plist"];
NSLog (@"@%", path);
NSMutableDictionary *dat = [NSMutableDictionary dictionary];
NSLog (@"@%", dat);
[dat setObject:data forKey:@"nthing"];
[dat writeToFile:path atomically:YES];

他のヒント

Why a plist file? A plist is nice for arrays and dictionaries, but I see no reason to store a simple string in a plist.

How about...

NSString *data = ...
NSError *error = nil;
[data writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top