I would like to output tags for each line with different tag names and want to save each in a file. I can write the file, but it is over writing. How do I write each and every line in a different file?
Input:
english titanic
leondradicapro kate
German Hotel hüßßan
tomhanks angleina
Output:
<language>english<language/>
<movie>titanic<movie/>
<Actor>leondradiacpro<Actor/>
<Actress>kate<Actress/>
<language>German<language/>
...
Code:
for (NSString *str in lineFile)
{
if([str hasPrefix:#"english "])
{
NSMutableArray *dd = [[NSMutableArray alloc] initWithArray:[[str stringByReplacingOccurrencesOfString:#"english" withString:#""] componentsSeparatedByString:#" "]];
NSArray *tag = [NSArray aarrayWithObjects:#"er",#"langauge",#"movie",#"actor",#"kate",nil];
NSMutableString *output =[[NSMutableString alloc] init];
NSUInteger tagindex =0;
for (NSString *words in word)
{
if(tagindex >=[tag count])
{
NSLog(#"dad");
break;
}
[output appendFormat:#"<%#>%#<%#>\n", [tag objectAtIndex:tagindex],words,[tag objectAtIndex:tagindex]];
NSLog(#"%#",output);
[output writeToFile:#"/Users/xx/Desktop/homework.txt" atomically:YES encoding:NSASCIIStringEncoding error:NULL];
tagindex++;
now i can able to read only the language and movie (1st line) how i can add second line and tag also
you need write file with c method, maybe the following method can help you
-(void)writeToFile:(NSString *)str:(NSString *) fileName
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *filePath=[NSString stringWithFormat:#"%#",fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
NSLog(#"file not exist,create it...");
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}else {
NSLog(#"file exist!!!");
}
FILE *file = fopen([filePath UTF8String], [#"ab+" UTF8String]);
if(file != NULL){
fseek(file, 0, SEEK_END);
}
int readSize = [data length];
fwrite((const void *)[data bytes], readSize, 1, file);
fclose(file);
}
Related
I am working on some file manipulation in iPhone project. Where i need to search files of specific extension. One option is to manually process each file & directory to find.
My Question is, Is there any simple way to do that ?
Thanks
see using NSFileManager you can get the files and bellow the condition with you can get file with particular extension, Its work in Document Directory ..
-(NSArray *)findFiles:(NSString *)extension
{
NSMutableArray *matches = [[NSMutableArray alloc]init];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] error:nil];
for (item in contents)
{
if ([[item pathExtension]isEqualToString:extension])
{
[matches addObject:item];
}
}
return matches;
}
use this array with your searched files.. get the return in NSArray type so use NSArray object to store this data...
i hope this helpful to you...
I have not found any thing which i could say is simple to do that & and finally i have to write my own code to do this. I am posting this here because maybe someone find this help full.
-(void)search{
#autoreleasepool {
NSString *baseDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *defFM = [NSFileManager defaultManager];
BOOL isDir = YES;
NSArray *fileTypes = [[NSArray alloc] initWithObjects:#"mp3",#"mp4",#"avi",nil];
NSMutableArray *mediaFiles = [self searchfiles:baseDir ofTypes:fileTypes];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"playlist.plist"];
if(![defFM fileExistsAtPath:filePath isDirectory:&isDir]){
[defFM createFileAtPath:filePath contents:nil attributes:nil];
}
NSMutableDictionary *playlistDict = [[NSMutableDictionary alloc]init];
for(NSString *path in mediaFiles){
NSLog(#"%#",path);
[playlistDict setValue:[NSNumber numberWithBool:YES] forKey:path];
}
[playlistDict writeToFile:filePath atomically:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:#"refreshplaylist" object:nil];
}
}
Now the recursive Method
-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
NSFileManager *defFM = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
for(NSString *path in dirPath){
BOOL isDir;
path = [basePath stringByAppendingPathComponent:path];
if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
[files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
}
}
NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
for(NSString *fileName in mediaFiles){
fileName = [basePath stringByAppendingPathComponent:fileName];
[files addObject:fileName];
}
return files;
}
What you need is a recursive method so that you can process sub-directories. The first of the following methods is public; the other private. Imagine they are implemented as static methods of a class called CocoaUtil:
CocoaUtil.h:
#interface CocoaUtil : NSObject
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder;
#end
CocoaUtil.m:
// Private Methods
#interface CocoaUtil ()
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder;
#end
#implementation CocoaUtil
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
{
return [CocoaUtil _findFilesWithExtension:extension
inFolder:folder
andSubFolder:nil];
}
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder
{
NSMutableArray *found = [NSMutableArray array];
NSString *fullPath = (subFolder != nil) ? [folder stringByAppendingPathComponent:subFolder] : folder;
NSFileManager *fileman = [NSFileManager defaultManager];
NSError *error;
NSArray *contents = [fileman contentsOfDirectoryAtPath:fullPath error:&error];
if (contents == nil)
{
NSLog(#"Failed to find files in folder '%#': %#", fullPath, [error localizedDescription]);
return nil;
}
for (NSString *file in contents)
{
NSString *subSubFolder = subFolder != nil ? [subFolder stringByAppendingPathComponent:file] : file;
fullPath = [folder stringByAppendingPathComponent:subSubFolder];
NSError *error = nil;
NSDictionary *attributes = [fileman attributesOfItemAtPath:fullPath error:&error];
if (attributes == nil)
{
NSLog(#"Failed to get attributes of file '%#': %#", fullPath, [error localizedDescription]);
continue;
}
NSString *type = [attributes objectForKey:NSFileType];
if (type == NSFileTypeDirectory)
{
NSArray *subContents = [CocoaUtil _findFilesWithExtension:extension inFolder:folder andSubFolder:subSubFolder];
if (subContents == nil)
return nil;
[found addObjectsFromArray:subContents];
}
else if (type == NSFileTypeRegular)
{
// Note: case sensitive comparison!
if ([[fullPath pathExtension] isEqualToString:extension])
{
[found addObject:fullPath];
}
}
}
return found;
}
#end
This will return an array containing the full path to every file with the specified file extension. Note that [NSString pathExtension] does not return the . of the file extension so be sure not to pass that in the extension parameter.
Yes we have direct method for NSArray below helps you
NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:#"a.png", #"a.jpg", #"a.pdf", #"h.png", #"f.png", nil];
NSLog(#"pathsMatchingExtensions----%#",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:#"png", nil]]);
//my output is
"a.png",
"h.png",
"f.png"
Like this way you can find your specific file extension
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
if ([filename hasSuffix:#".doc"]) { //change the suffix to what you are looking for
[arrayListofFileName addObject:[filename stringByDeletingPathExtension]];
}
}
Use below code
NSArray *myFiles = [myBundle pathsForResourcesOfType:#"Your File extension"
inDirectory:nil];
For my new project. i have loaded my csv file content as a NSString.
First, i need to split this by newline, then split each line by comma.
How can i loop all this? Could you please help me?
CSV Content
"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/2012","5:30pm",+18.59,3060.34,3076.44,3043.30,0
ViewController.m
NSString* pathToFile = [[NSBundle mainBundle] pathForResource: #"quotes" ofType: #"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
NSLog(#"Error reading file.");
}
NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for(int i=0; i<[array count]; i++){
//
}
Might want to look into NSMutableArray.
// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
[data replaceObjectAtIndex: i
withObject: [[data objectAtIndex: i] componentsSeparatedByString: #","]];
}
Relatedly, Dave DeLong has a proper library to address this need: https://github.com/davedelong/CHCSVParser
I have my sqlite database. now i want syncing with icloud. I read blogs saying sqlite syncing with icloud is not supported. Either go for core data OR "Do what exactly core data does".
Now it is not posible for me to go for core data.So like second option "Do something similar to how CoreData syncs sqlite DBs: send "transaction logs" to iCloud instead and build each local sqlite file off of those."
please can anyone share any sample code for "transaction log" of sqlite OR can expalin in detail stepwise what i need to do?
1) I followed this link to create xml. You can download respective api from its github.Link is - http://arashpayan.com/blog/2009/01/14/apxml-nsxmldocument-substitute-for-iphoneipod-touch/
2) on button click:
-(IBAction) btniCloudPressed:(id)sender
{
// create the document with it’s root element
APDocument *doc = [[APDocument alloc] initWithRootElement:[APElement elementWithName:#"Properties"]];
APElement *rootElement = [doc rootElement]; // retrieves same element we created the line above
NSMutableArray *addrList = [[NSMutableArray alloc] init];
NSString *select_query;
const char *select_stmt;
sqlite3_stmt *compiled_stmt;
if (sqlite3_open([[app getDBPath] UTF8String], &dbconn) == SQLITE_OK)
{
select_query = [NSString stringWithFormat:#"SELECT * FROM Properties"];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
NSString *addr = [NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,5)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,6)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,7)]];
//NSLog(#"%#",addr);
[addrList addObject:addr];
}
sqlite3_finalize(compiled_stmt);
}
else
{
NSLog(#"Error while creating detail view statement. '%s'", sqlite3_errmsg(dbconn));
}
}
for(int i =0 ; i < [addrList count]; i++)
{
NSArray *addr = [[NSArray alloc] initWithArray:[[addrList objectAtIndex:i] componentsSeparatedByString:#"#"]];
APElement *property = [APElement elementWithName:#"Property"];
[property addAttributeNamed:#"id" withValue:[addr objectAtIndex:0]];
[property addAttributeNamed:#"street" withValue:[addr objectAtIndex:1]];
[property addAttributeNamed:#"city" withValue:[addr objectAtIndex:2]];
[property addAttributeNamed:#"state" withValue:[addr objectAtIndex:3]];
[property addAttributeNamed:#"zip" withValue:[addr objectAtIndex:4]];
[property addAttributeNamed:#"status" withValue:[addr objectAtIndex:5]];
[property addAttributeNamed:#"lastupdated" withValue:[addr objectAtIndex:6]];
[property addAttributeNamed:#"deleted" withValue:[addr objectAtIndex:7]];
[rootElement addChild:property];
[property release];
APElement *fullscore = [APElement elementWithName:#"FullScoreReport"];
[property addChild:fullscore];
[fullscore release];
select_query = [NSString stringWithFormat:#"SELECT AnsNo,Answer,AnswerScore,MaxScore,AnsIndex FROM FullScoreReport WHERE Addr_ID = %#",[addr objectAtIndex:0]];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
APElement *answer = [APElement elementWithName:#"Answer"];
[answer addAttributeNamed:#"AnsNo" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]]];
[answer addAttributeNamed:#"Answer" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]]];
[answer addAttributeNamed:#"AnswerScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]]];
[answer addAttributeNamed:#"MaxScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]]];
[answer addAttributeNamed:#"AnsIndex" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]]];
[fullscore addChild:answer];
[answer release];
}
sqlite3_finalize(compiled_stmt);
}
}
sqlite3_close(dbconn);
NSString *prettyXML = [doc prettyXML];
NSLog(#"\n\n%#",prettyXML);
//***** PARSE XML FILE *****
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Properties.xml" ];
NSData *file = [NSData dataWithBytes:[prettyXML UTF8String] length:strlen([prettyXML UTF8String])];
[file writeToFile:path atomically:YES];
NSString *fileName = [NSString stringWithFormat:#"Properties.xml"];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:fileName];
MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
mydoc.xmlContent = prettyXML;
[mydoc saveToURL:[mydoc fileURL]forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"XML: Synced with icloud");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iCloud Syncing" message:#"Successfully synced with iCloud." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
NSLog(#"XML: Syncing FAILED with icloud");
}];
}
3)MyDocument.h file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSString *xmlContent;
#end
4)MyDocument.m file
#import "MyDocument.h"
#implementation MyDocument
#synthesize xmlContent,zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
// NSLog(#"* ---> typename: %#",typeName);
self.xmlContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return [NSData dataWithBytes:[self.xmlContent UTF8String] length:[self.xmlContent length]];
}
#end
5) now in ur appdelegate
- (void)loadData:(NSMetadataQuery *)queryData
{
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSNumber *filesize = [item valueForAttribute:NSMetadataItemFSSizeKey];
NSDate *updated = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
NSLog(#"%# (%# bytes, updated %#) ", filename, filesize, updated);
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"Properties"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"XML: Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
//NSString *xmlFile = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
//NSLog(#"%#",xmlFile);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
//We hold here until the parser finishes execution
[parser release];
}
else
{
NSLog(#"XML: failed to open from iCloud");
}
}];
}
}
}
6) now in parser method fetch data and insert/update as needed in database.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)nameSpaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"Property"])
{
NSLog(#"Property attributes : %#|%#|%#|%#|%#|%#|%#|%#", [attributeDict objectForKey:#"id"],[attributeDict objectForKey:#"street"], [attributeDict objectForKey:#"city"], [attributeDict objectForKey:#"state"],[attributeDict objectForKey:#"zip"],[attributeDict objectForKey:#"status"],[attributeDict objectForKey:#"lastupdated"],[attributeDict objectForKey:#"deleted"]);
}
//like this way fetch all data and insert in db
}
i am using the code below to save an image in the NSDocumentDirectory
-(BOOL)saveImage:(UIImage *)image name:(NSString *)name{
NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString pathWithComponents:[NSArray arrayWithObjects:dir, name, nil]];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
if (!ok) {
NSLog(#"Error creating file %#", path);
}
else {
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(image)];
[myFileHandle closeFile];
}
return ok;
}
the name is usually the url of where the image was downloaded.
is there a constraint on the length of the file name? you know sometimes urls may be super long...
thank you
Taking a look at the PATH_MAX constant in syslimits.h:91
...
#define PATH_MAX 1024 /* max bytes in pathname */
...
You can test this yourself by doing :
NSLog(#"%i", PATH_MAX);
just to make sure.
I find this link everywhere for SQLite sample code (http://developer.apple.com/library/ios/#samplecode/SQLiteBooks/index.html) but either it has been removed or changed to another location.. I couldn't find it in google searches.. Does anyone know any other link to the code or any other good sample code for SQLite?
May be this is useful to you.
http://www.switchonthecode.com/tutorials/using-sqlite-on-the-iphone
http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
http://www.icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/
You can use this class and send query in this class and get all functionality of sqlite using this class
.h
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#interface DBLib : NSObject {
sqlite3 *database;
NSString *path;
}
- (NSString *)getDatabasePath:(NSString*)DBName;
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName;
- (void)initializeDatabase:(NSString*)DBName;
-(NSMutableArray*)GetListBySQL:(NSString*)SQL;
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME;
-(BOOL)deleteQuery:(NSString *)query;
#end
.m
#import "DBLib.h"
#implementation DBLib
#pragma mark Database methods
- (NSString *)getDatabasePath:(NSString*)DBName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:DBName];
}
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DBName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DBName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[error localizedDescription] ]];
NSAssert1(0, #"%#", errString);
}
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase:(NSString*)DBName {
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
path = [documentsDirectory stringByAppendingPathComponent:DBName];
NSStringEncoding enc = [NSString defaultCStringEncoding];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
//TRUE
NSLog(#"Successfully opened-sqlite3");
}
else
{
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSLog(#"closed");
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
// Additional error handling, as appropriate...
}
}
-(NSMutableArray*)GetListBySQL:(NSString*)SQL
{
[self initializeDatabase:#"DBNAME"];
NSMutableArray* Array;
Array=[[NSMutableArray alloc]init];
NSStringEncoding enc = [NSString defaultCStringEncoding];
sqlite3_stmt *select_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &select_statement, NULL) != SQLITE_OK) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
}
int columncount=sqlite3_column_count(select_statement);
NSMutableDictionary* dic;
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
dic=[[NSMutableDictionary alloc]init];
for(int j=0;j<columncount;j++)
{
if(sqlite3_column_text(select_statement, j)!=nil)
[dic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(select_statement, j)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
else
[dic setObject:#"" forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
}
[Array addObject:dic];
[dic release];
}
sqlite3_finalize(select_statement);
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray: Array];
[Array release];
return arr;
}
//Method for Datbase
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQLColumns=#"";
NSString* SQLValues=#"";
NSString* SQL=#"";
//Chekc Wheather Insert or update?
BOOL IsNew=NO;;
if([[objDic valueForKey:PrimaryKey] intValue]==0)
{
IsNew=YES;
}
NSArray* Keys=[objDic allKeys];
NSLog(#"%#",Keys);
if(IsNew)
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#,",SQLColumns,[Keys objectAtIndex:i]];
SQLValues=[NSString stringWithFormat:#"%#?,",SQLValues];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
SQLValues=[SQLValues substringToIndex:[SQLValues length]-1];
}
SQL=[NSString stringWithFormat:#"INSERT INTO %# (%#) Values(%#)",TABLE_NAME,SQLColumns,SQLValues];
}
else
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#=?,",SQLColumns,[Keys objectAtIndex:i]];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
}
SQL=[NSString stringWithFormat:#"UPDATE %# SET %# WHERE %#=?",TABLE_NAME,SQLColumns,PrimaryKey];
//NSLog(sql);
}
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int intBindIndex=1;
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
sqlite3_bind_text(insert_statement,intBindIndex,[[objDic valueForKey:[Keys objectAtIndex:i]] UTF8String],-1, SQLITE_STATIC);
intBindIndex++;
}
}
if(!IsNew)
{
sqlite3_bind_text(insert_statement,Keys.count,[[objDic valueForKey:PrimaryKey] UTF8String],-1, SQLITE_STATIC);
}
int result;
result=sqlite3_step(insert_statement);
if(IsNew)
{
[objDic setObject:[NSString stringWithFormat:#"%d",sqlite3_last_insert_rowid(database)] forKey:PrimaryKey];
}
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
-(BOOL)deleteQuery:(NSString *)query
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQL=#"";
SQL=[NSString stringWithString:query];
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int result;
result=sqlite3_step(insert_statement);
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
#end