remove some signs from a txt file - objective-c

i am saving a NSMutuablearray to a text file, he has NSNmbers in it .
when i open it (it sent to my emal) i see :
<integer>-13</integer>
<integer>-80</integer>
<integer>-15</integer>
i want ONLY the numbers without this <integer> sign.
there is a way of removing that? or put that numbers not in nsmutuable ?
code :
//add numbers
for(int i=0;i<417;i++)
{
int x= [globals sharedGlobals].bufBuf[i];
NSNumber* myNumber = [NSNumber numberWithInt: x];
[samples addObject:myNumber];
}
//create file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFileName = [NSString stringWithFormat:#"%#/samplesTest.txt", documentsDirectory];
[samples writeToFile:fullFileName atomically:NO];
thanks.

You can prepare a string with your numbers, and save it to the file:
NSArray *numbers =
[NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
nil
];
NSString *res = [numbers componentsJoinedByString:#","];
NSError *error;
[res writeToFile:fullFileName atomically:NO encoding:NSUTF8StringEncoding
error:&error];

Related

Objective-C save and load files

Hello I am trying to load data from a file
This function save the data to a file in documents folder
- (IBAction)saveUser:(id)sender{
NSString *name = [nameField stringValue];
NSString *weight = [weightField stringValue];
NSDate *date = [datePick dateValue];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[nameField stringValue] forKey:#"name"];
[dict setValue:[weightField stringValue] forKey:#"weight"];
[dict setValue:date forKey:#"date"];
[dict writeToFile:name atomically:YES];
}
However when I try to load the file and get the data from it I cant, could someone tell me how this is done done.
Edit to show loadFunction
-(IBAction)loadUser:(id)sender{
NSString *weight = [weightField stringValue];
NSDate *date = [datePick dateValue];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *loadPath = [documentsDirectory stringByAppendingPathComponent:name];
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: name];
NSLog(#"%#", weight);
}
To fix your answer. here is a code that works, you pretty much did not give a filename.
NSString *filename = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
And in your line where you write the file :
[dict writeToFile:name atomically:YES];
you must change name to filename, like this
[dict writeToFile:filename atomically:YES];
And in your load data method :
NSString *filename = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSLog(#"The weight is : %#", [savedData valueForKey:#"weight"]);
The following seems to do what you intend (minus the UI element dependencies in your code):
#import <Foundation/Foundation.h>
static NSString *pathToDocuments(void) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:#"SomeName" forKey:#"name"];
[dict setValue:#"SomeWeight" forKey:#"weight"];
[dict setValue:[NSDate date] forKey:#"date"];
NSString *filePath = [pathToDocuments() stringByAppendingPathComponent:[dict objectForKey:#"name"]];
[dict writeToFile:filePath atomically:YES];
[dict release]; dict = nil;
NSLog(#"%s - Confirming dict is nil: %#",__FUNCTION__,dict);
dict = [[NSDictionary dictionaryWithContentsOfFile:filePath] mutableCopy];
NSLog(#"%s - weight = %#",__FUNCTION__,[dict objectForKey:#"weight"] );
[p release];
}
This prints the following to the console:
2012-10-19 06:40:38.691 Untitled[10633:707] main - Confirming dict is nil: (null)
2012-10-19 06:40:38.693 Untitled[10633:707] main - weight = SomeWeight
EDIT:
That said, I think the problem may be the file path in loadUser...

Saving data from Twitter feed parsed with JSON into Plist

I have a UITableView populated by a feed from searchtwitter.com. I also have a details table with an image and UILabel. I have all this working, but I want to add a UIButton on the detail page that will save the UIImage and the label into a property list. I'm very new to this; here is what I have so far (not working).
- (IBAction)SaveFriend:(id)sender
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *plistPath = [documentDirectory stringByAppendingPathComponent:#"TwitterFriends.plist"];
NSDictionary * tweet = [[NSDictionary alloc]init];
NSString *text = [tweet objectForKey:#"from_user"];
NSString *user = [tweet objectForKey:#"from_user_name"];
personName.text = text;
personInfo.text = user;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, personInfo, nil] forKeys:[NSArray arrayWithObjects: #"Name", #"info", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[tweet writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
}
Instead of using a .plist, try using an NSArray or NSMutableArray and then the writeToFile method. For example:
NSMutableArray *temp = [NSMutableArray new];
[temp addObject:image];
[temp addObject:label];
[temp writeToFile:[self saveFilePath:#"filename"] atomically:YES];
//Returns the saved information path
- (NSString*) saveFilePath: (NSString *) add
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filename = [path stringByAppendingPathComponent:add];
return filename;
}

Can't record or play with a simple recorder?

I have 2 classes, a record and a player. In my main scene, I create an instance of them and play and record. But, as I see, it only records and somehow does not play (the file is not there!)
Here is the code for both :
-(void)record {
NSArray *dirPaths;
NSString *docsDir;
NSString *sound= #"sound0.caf" ;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:sound];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax],
AVEncoderAudioQualityKey, nil];
NSError *error;
myRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:settings error:&error];
if (myRecorder) {
NSLog(#"rec");
[myRecorder prepareToRecord];
myRecorder.meteringEnabled = YES;
[myRecorder record];
} else
NSLog( #"error" );
}
I can see the log of rec.
-(void)play {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath1 = #"sound0.caf" ;
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath1];
BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:soundFilePath1];
if(isMyFileThere) {
NSLog(#"PLAY");
avPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:NULL];
avPlayer1.volume = 8.0;
avPlayer1.delegate = self;
[avPlayer1 play];
}
}
I DONT SEE THE LOG OF PLAY !
I call them both with:
recInst=[recorder alloc]; //to rec
[recInst record];
plyInst=[player alloc]; //play
[plyInst play];
and to stop the recorder:
- (void)stopRecorder {
NSLog(#"stopRecordings");
[myRecorder stop];
//[myRecorder release];
}
What's wrong here? Thanks.
In your record method, you're appending the file name to the path with:
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:#"sound0.caf"];
You do not do that in your play method, so it's looking for the file in whatever the current working directory is, rather than the Documents directory.
You need to do:
NSString *soundFilePath1 = [docsDir stringByAppendingPathComponent:#"sound0.caf"];
instead of:
NSString *soundFilePath1 = #"sound0.caf" ;
And just another note: soundFilePath and soundFilePath1 are both local variables. Therefore, they are not visible outside their respective methods. Thus, it's not necessary to give them different names. You can call them both soundFilePath and there will not be a conflict.

Parsing a JSON text

With the following way...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"/lkj/"]];
NSString *fileName = [NSString stringWithFormat:#"/sandbox/2012_05_11.json"];
[[self restClient] loadFile:fileName intoPath:path];
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:path];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from inside of "menu"
NSString *message = (NSString *) [data objectForKey:#"message"];
NSString *name = (NSString *) [data objectForKey:#"name"];
namegroup.text = [NSString stringWithFormat:#"%# %#",name, message];
...I am trying to parse a document I have previously made with other code...
{"message":["Untitled1a","Untitled2a","Untitled3a"],"name":["Untitled1b","Untitled2b","Untitled3b"]}
with the code above though, in name group.text, this appears...
(untitled, untitled, untitled) (untitled, untitled, untitled)
...but what I would like to do is to allocate many UITextFields, each of them in pairs, (2, 2, 2..), one field which displays the name and the other the message, so pair up 1a with 1b, 2a with 2b... obviously the fields won't be Untitled1a, but "how are you"...
But I can't seem to fix this issue!! Please help!!
You may try something like this:
NSArray *message = [data objectForKey:#"message"];
NSArray *name = [data objectForKey:#"name"];
NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:message forKeys:name];
for (NSString* Key in [Dictionary allKeys]){
NSLog(#"%# %#",Key,[Dictionary objectForKey:Key]);
}

Creating new dictionary when saving data to plist

So I am saving 3 NSStrings from 3 UITextFields to a property list. This works fine, but everytime I save something new, the app overwrites the data that was saved before. So basically there is only 1 Dictionary used, but i want the app to create a new dictionary everytime i save something new, so that no data gets deleted. I have no Idea how i could do this, so please help me!! :)
Code:
NSMutableArray *array = [NSMutableArray arrayWithCapacity:3];
NSArray *keys = [NSArray arrayWithObjects:#"1",#"2",#"3", nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
[array writeToFile:path atomically:YES];
Use a NSMutableArray to which you add each new dictionary object and then write that array to data.plist.
Is there any reason why you alloc the array with capacity? I would just use [[NSMutableArray alloc] init], then add your objects.
Also, I had trouble saving NSMutableDictionaries in the NSUserDefaults, so what I ended up doing was just saving the dictionary to a file with
[dict writeToFile:filePath atomically:NO];
and initWithContentsOfFile or initWithContentsOfURL depending if I wanted to load a local or Internet file.
I should add, you can writeToFile, initWithContentsOf* for NSMutableArray as well.
Ok I've got it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSLog(#"path='%#'",path);
NSFileManager *nfm = [[NSFileManager alloc] init];
if([nfm fileExistsAtPath:path])
{
// if file exists, get its contents, add more entries and write back
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSArray *keys = [NSArray arrayWithObjects:#"4",#"5",#"6",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSLog(#"modified array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write appended file");
return;
}
} else {
// if file doesn't exist, create a new one
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *keys = [NSArray arrayWithObjects:#"1",#"2",#"3",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSLog(#"new array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write new file");
return;
}
}