How to use NSData and NSBundle together?

Hi everyone, I have NSData to create a file *.txt and then I read it by using NSBundle, but it do not working correctly. Can anybody help me?

Posted on Jan 23, 2013 7:54 AM

Reply
9 replies

Jan 23, 2013 8:08 AM in response to red_menace

Thanks for your care. I use Xcode 4.5.2, and build on iOS 6.0. Here my code :

-(void)WriteToFile

{

NSString * temp=[[NSString alloc]init];

for(NSString *word in listMenu)

{

NSString* word1=[NSString stringWithFormat:@"%@#Waiting",word];

temp=[NSString stringWithFormat:@"%@?%@",temp,word1];

}

[self creatFile:[[UIDevice currentDevice]name] data:temp];

}


-(void)creatFile:(NSString *)fileName data:(NSString*)data

{

NSString *pathFile=[NSString stringWithFormat:@"%@_%d.txt",fileName,Ordinal];

NSData * dataPath=[data dataUsingEncoding:NSUTF8StringEncoding];

[dataPath writeToFile:pathFile atomically:YES];

}

I use function "WritetoFile" to create file and I use this code to read file:

-(void)ReadFile

{

OrdinalNumber=1;

NSString * nameFile=[NSString stringWithFormat:@"%@_%d",[[UIDevice currentDevice]name],OrdinalNumber];

NSString *pathname=[[NSBundle mainBundle]pathForResource:nameFile ofType:@"txt" inDirectory:@"/"];

NSString *wordstring =[NSString stringWithContentsOfFile:pathname];

NSArray *temp=[wordstring componentsSeparatedByString:@"?"];

listMenu=[[NSMutableArray alloc]initWithArray:temp];

[listMenu removeObjectAtIndex:0];

}

However, I just recieve the previous data, not current. What's wrong with it?

Jan 24, 2013 7:12 AM in response to letatanu

WriteToFile is successful


You might want to check that - I can't tell what winds up as the write path, but it doesn't look like you are writing to the same file path that you are reading from. If you are trying to write to the application bundle (where you are reading from) that is not a good idea. Apart from reading and writing a file, exactly what is it you are wanting to do?

Jan 24, 2013 5:53 PM in response to letatanu

The NSBundle class has some methods for finding resources in the application bundle, if that is where your file is located. You just need to provide a valid path for your file read/write, wherever that is. If you are trying to use some kind of preference, look at NSUserDefaults, if you are using one of the standard directories such as the temporary directory, look at NSFileManager, etc.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to use NSData and NSBundle together?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.