2014-03-02 64 views
-1

您好我正在研究iOS中的简单激活应用程序。我想保存的UDID在文本文件中,平等的文本文件与当前的UDID,但我不能保存UDID到文本文件将udid字符串保存到文本文件

NSString *udid = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; 

NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"h" ofType:@"txt"]]; 

NSMutableString *text = [NSMutableString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil]; 

NSLog(@"text is : %@",text); 

NSString *text1 = text; 

NSString *y; 

if ([text1 isEqualToString:y]) { 

    [text appendString:udid]; 

    NSString *myURLString = [fileURL absoluteString]; 

    [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil]; 

    NSLog(@"saved to file : %@",text); 

}else { 

    if ([text isEqualToString:udid]) { 

     NSLog(@"yes thats it"); 
     lable.text = @"yes thats it"; 

    }else { 
     NSLog(@"nononono"); 
     exit(0); 


    } 
} 

回答

0

有你的代码的几个问题。开始于:

if ([text1 isEqualToString:y]) { 

其中是“y”定义或声明?

另外,在写入文件时,您从不查看错误参数。更改此:

[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil]; 

这样:

NSError *error; 

BOOL success = [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:&error]; 

if(NO == success) 
{ 
    NSLog(@"error from writing to %@ is %@", myURLString, [error localizedDescription]); 
} 

至于你正在运行成什么样的错误,你可能有一个更好的线索。

最后,通过您的评论,您已经明确表示您正在尝试将文件直接写入应用程序包中。这是一个很大的(沙箱)不,不。

相反的:

NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"h" ofType:@"txt"]]; 

做到这一点,而不是:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *basePath = [paths firstObject]; 
NSURL *fileURL = [NSURL fileURLWithPath:[basePath stringByAppendingString:@"/h.txt"]]; 

,这将您的文件保存到文件目录,这是一个合法的地方保存文件。

+0

它给我:写入文件时出错:///Users/mji/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/C48463FB-F7F0-47AD-A40A-958A3583C29E/active%20text。 app/h.txt是操作无法完成。 (可可错误4.) – user3001228

+0

你不应该试图写入应用程序的包,这是不允许的。 –

+0

现在它给了我这个当我想保存udid文件写入文件错误:///Users/mji/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/C48463FB-F7F0-47AD-A40A -958A3583C29E/Documents/h.txt为(null) – user3001228

相关问题