iPhone : How to get each element from QR code vCard? - iphone

I am developing one simple application which is used to read the QR code vCard and display the details of the contact information in the QR code vCard. I am able to scan the vCard and get the details about the contact as follows
BEGIN:VCARD
VERSION:2.1
N:XX;XXXXXXXX
FN:XXXXXXXXX XX
TEL;WORK;VOICE:91999999999
EMAIL;WORK;INTERNET:sac#gmail.com
END:VCARD
But I need to parse each element in it. How to parse the details and what are the ways to parse?

The documentation points to this method:
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results){
NSString *upcString = symbol.data;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Scanned UPC" message:[NSString stringWithFormat:#"The UPC read was: %#", upcString] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[reader dismissModalViewControllerAnimated: YES];
}
}
i would first see what it returns maybe try looping the dictionary for additional data

Well its being quite a long time that this question is asked. But answering now might also help someone who is navigated to this page. You can use the below method for reference to parse the VCF data.
NSString *str = [NSString stringWithString:response.vcfString];
NSArray *subStrings = [str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\n"]];
NSArray *getData = [[NSArray alloc]init];
NSString *arr = #"";
for (int i=0;i<[subStrings count];i++)
{
arr = [subStrings objectAtIndex:i];
NSArray *abc = [arr componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#";"]];
if([[abc objectAtIndex:0] isEqualToString:#"FN"])
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"] ];
if([getData count] > 1)
fullName = [getData objectAtIndex:1];
}
else if([[abc objectAtIndex:0] isEqualToString:#"N"])
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
lastName = [getData objectAtIndex:1];
FirstName = [abc objectAtIndex:2];
}
else if([[abc objectAtIndex:0] isEqualToString:#"TITLE"])
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
title = [getData objectAtIndex:1];
}
else if([[abc objectAtIndex:0] isEqualToString:#"TEL"])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
if([abc count] == 3)
{
getData=[[abc objectAtIndex:2] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([[abc objectAtIndex:1] isEqualToString:#"WORK"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Tel"];
}
else if([[abc objectAtIndex:1] isEqualToString:#"CELL"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Tel"];
}
}
else if([abc count] == 4)
{
getData=[[abc objectAtIndex:3] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([[abc objectAtIndex:1] isEqualToString:#"WORK"] && [[abc objectAtIndex:2] isEqualToString:#"FAX"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Tel"];
}
}
else
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([[getData objectAtIndex:0] isEqualToString:#"WORK"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Tel"];
}
else if([[getData objectAtIndex:0] isEqualToString:#"FAX"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Tel"];
}
}
[_telList addObject:dict];
}
else if([[abc objectAtIndex:0] isEqualToString:#"EMAIL"])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
if([abc count] == 3)
{
getData=[[abc objectAtIndex:2] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([[abc objectAtIndex:1] isEqualToString:#"WORK"])
{
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Email"];
}
}
else
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Email"];
}
[_emailList addObject:dict];
}
else if([[abc objectAtIndex:0] isEqualToString:#"ORG"])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
if([abc count] == 5)
{
getData=[[abc objectAtIndex:2] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([[abc objectAtIndex:1] isEqualToString:#"WORK"])
{
NSString *orgStr = #"";
if([getData count] > 1)
{
orgStr = [getData objectAtIndex:1];
}
[dict setObject:[orgStr stringByAppendingString:[abc objectAtIndex:4]] forKey:#"Org"];
}
}
else
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Org"];
}
[_orgList addObject:dict];
}
else if([[abc objectAtIndex:0] isEqualToString:#"ADR"])
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if([abc count] == 9)
{
[dict setObject:[abc objectAtIndex:4] forKey:#"Add"];
[dict setObject:[abc objectAtIndex:8] forKey:#"Country"];
[dict setObject:[abc objectAtIndex:7] forKey:#"Zip"];
[dict setObject:[abc objectAtIndex:5] forKey:#"City"];
}
else
{
}
[_addrList addObject:dict];
}
else if([[abc objectAtIndex:0] isEqualToString:#"URL"])
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if([abc count] == 3)
{
getData=[[abc objectAtIndex:2] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Url"];
}
else
{
getData=[[abc objectAtIndex:1] componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#":"]];
if([getData count] > 1)
[dict setObject:[getData objectAtIndex:1] forKey:#"Url"];
}
[_urlList addObject:dict];
}
else
{
}
}
NSLog(#"Details: \nFull Name - %#\nLast Name - %#\nFirst Name - %#\ntitle - %#\nEmail - %#\norg - %#\nAddress - %#\nUrl - %#", fullName,lastName,FirstName,title,[[_emailList valueForKey:#"description"] componentsJoinedByString:#""],[_orgList description],[_addrList description],[_urlList description] );

you can use Encoder of QRCode
Encoder

You can use CNContactVCardSerialization to get CNContact Object from data
import Contacts
if let data = str.data(using: .utf8) {
do {
let contacts = try CNContactVCardSerialization.contacts(with: data)
let contact = contacts.first
print("\(String(describing: contact?.familyName))")
return contact
} catch {
print("Contact Error: \(error.localizedDescription)")
}
}

Related

how to sort an array by integer

i am trying to sort my score board but the score board is sorted by name but i want sort it by score i.e (high to low) score plese help to solve this.i stored the playername and score details in one label.
please help me
thanks in advance
asd 45
asd 66
rrr 55
tes 42
i want to show like
asd 66
rrr 55
asd 45
tes 42
-(void)btnSaveScore
{
if(!dictWinData)
dictWinData = [[NSMutableDictionary alloc] init];
array = [[NSMutableArray alloc] init];
array = [[[NSUserDefaults standardUserDefaults] valueForKey:#"ScoreName"] mutableCopy];
if([array count] == 0)
{
array = [[NSMutableArray alloc] init];
}
NSString *strName = [NSString stringWithFormat:#"%#",strNameOFPlayer];
NSString *strScore = [NSString stringWithFormat:#"%#",[NSString stringWithFormat:#"%d",iTap]];
int intScore = iTap;
NSLog(#"iTap data is:--> %d",intScore);
if([strNameOFPlayer length]==7)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 6)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 5)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 4)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 3)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 2)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 1)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sorters];
[sorters release];
NSUserDefaults *dfltsData = [NSUserDefaults standardUserDefaults];
[dfltsData setObject:sortedArray forKey:#"ScoreName"];
// [dfltsData setObject:array forKey:#"ScoreCard"];
[dfltsData synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Score is saved."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
Here you are adding the string (containing name and score) to the array. Instead, create a model class with the name (NSString*) and score (NSNumber*) members and add them to the array.
For sorting,
NSArray *sortedArray = [yourUnsortedArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
if ([[obj1 score] integerValue] > [[obj2 score] integerValue]) {
return NSOrderedDescending;
}
if ([[obj1 score] integerValue] < [[obj2 score] integerValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];

can i sort stored score in nsuserdefaults?

i am developing game application ,in that app i am storing name,score in nsuserdefaults ....but
the according to my requirement i want to store name and score (high to low) based on score ....is there any solution for sorting score in nsuserdefaults... i want show my high score on top
thank's in adv
-(void)btnSaveScore
{
if(!dictWinData)
dictWinData = [[NSMutableDictionary alloc] init];
array = [[NSMutableArray alloc] init];
array = [[[NSUserDefaults standardUserDefaults] valueForKey:#"ScoreName"] mutableCopy];
if([array count] == 0)
{
array = [[NSMutableArray alloc] init];
}
NSString *strName = [NSString stringWithFormat:#"%#",strNameOFPlayer];
NSString *strScore = [NSString stringWithFormat:#"%#",[NSString stringWithFormat:#"%d",iTap]];
if([strNameOFPlayer length]==7)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 6)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 5)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 4)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 3)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 2)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
else if ([strNameOFPlayer length] == 1)
[array addObject:[NSString stringWithFormat:#"%# %#",strName,strScore]];
NSUserDefaults *dfltsData = [NSUserDefaults standardUserDefaults];
[dfltsData setObject:array forKey:#"ScoreName"];
[dfltsData synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Score is saved."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
please help me out
Get array from NSUserDefault like this:
NSMutableArray *arrScores = [[NSUserDefaults standardUserDefaults] ObjectforKey:#"ScoreName"];
Now sort arrScores should only contain strScore value only using below method:
-(NSMutableArray *)sortByfloatvalue:(NSMutableArray *)array
{
for(int i=0;i<[array count];i++)
{
for(int j=i+1;j<[array count];j++)
{
if([[array objectAtIndex:i] floatValue] < [[array objectAtIndex:j] floatValue])
{
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
return array;
}

how to capture the required values from a URL

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
http://gmail.com?access_token=ab8w4azq2xv3dr4ab37vvzmh&token_type=bearer&expires_in=3600
How can I capture the value of the access_token which in this example is ab8w4azq2xv3dr4ab37vvzmh?
This code should do it:
- (NSString *)extractToken:(NSURL *)URL
{
NSString *urlString = [URL absoluteString];
NSRange start = [urlString rangeOfString:#"access_token="];
if (start.location != NSNotFound)
{
NSString *token = [urlString substringFromIndex:start.location+start.length];
NSRange end = [token rangeOfString:#"&"];
if (end.location != NSNotFound)
{
//trim off other parameters
token = [token substringToIndex:end.location];
}
return token;
}
//not found
return nil;
}
Alternatively, here is a more general solution that will extract all the query parameters into a dictionary:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([parts count] > 1)
{
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result setObject:value forKey:key];
}
}
return result;
}
Good Category for NSDictionary:
#import "NSDictionary+URL.h"
#implementation NSDictionary (URL)
+ (NSDictionary *)dictionaryWithUrlString:(NSString *)urlString{
NSRange urlRange = [urlString rangeOfString:#"?"];
if(urlRange.length>0){
urlString = [urlString substringFromIndex:urlRange.length+urlRange.location];
}
NSArray *pairsArray = [urlString componentsSeparatedByString:#"&"];
NSMutableDictionary *parametersDictionary = [[NSMutableDictionary alloc] initWithCapacity:[pairsArray count]];
for(NSString *pairString in pairsArray){
NSArray *valuesArray = [pairString componentsSeparatedByString:#"="];
if([valuesArray count]==2){
[parametersDictionary setValue:[valuesArray objectAtIndex:1] forKey:[valuesArray objectAtIndex:0]];
}
}
return [parametersDictionary autorelease];
}
#end
NSMutableDictionary *querycomponent = [[NSMutableDictionary alloc] init];
if (![query isEqualToString:#""]){
NSArray *queryArray = [query componentsSeparatedByString:#"&"];
for (NSString *subquery in queryArray){
NSArray *subqueryArray = [subquery componentsSeparatedByString:#"="];
NSString *key = [subqueryArray objectAtIndex:0];
NSString *val = [subqueryArray objectAtIndex:1];
[querycomponent setObject:val forKey:key];
}
NSLog(#"querycomponent %#",querycomponent);
}

SQLITE Database Error 14

I'm developing a game where there are 4 buildings and in these buildings, there are 3 stages inside. The player can play the stages one by one, from one building to another, however, when they have finished one cycle (eg. going from building 1 stage 1 to building 4 stage 3) I keep getting this error where it's an error 14 (SQLITE_CANTOPEN) whenever the player clicks on another building. It keeps happening every single time I test the app. Can anyone help me? :S
edit: sorry, here's the code I used to open the window to access the game:
NSArray *bldgLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_BUILDING_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.selectedArea], #"i", nil]];
NSLog(#"bldgLevels: %#", bldgLevels);
NSLog(#"getting player levels");
NSArray *playerLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_UNLOCKED_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i", nil]];
NSLog(#"playerLevels: %#", playerLevels);
int i = 0;
while (i < [bldgLevels count])
{
NSDictionary *bldgLevel = (NSDictionary *)[bldgLevels objectAtIndex: i];
int levelId = [(NSNumber *)[bldgLevel objectForKey: #"level_id"] intValue];
int indexOrder = [(NSNumber *)[bldgLevel objectForKey: #"index_order"] intValue];
data = [BldgLevelData createObject];
data.levelId = levelId;
data.levelName = (NSString *)[bldgLevel objectForKey: #"name"];
data.rescuedPtsRequired = [(NSNumber *)[bldgLevel objectForKey: #"rescued_required"] intValue];
data.minPtsToComplete = [(NSNumber *)[bldgLevel objectForKey: #"min_pts"] intValue];
data.lastPlayed = #"";
data.dateAdded = #"";
data.isNew = NO;
data.isCompleted = NO;
data.isLocked = YES;
// Group levels together by their index order
if (indexOrder == 1) { groupId++; }
data.groupId = groupId;
data.indexOrder = indexOrder;
int j = 0;
while (j < [playerLevels count])
{
NSDictionary *playerLevel = (NSDictionary *)[playerLevels objectAtIndex: j];
int playerLevelId = [(NSNumber *)[playerLevel objectForKey: #"level_id"] intValue];
if (levelId == playerLevelId)
{
data.rescuedHighScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_highscore"] intValue];
data.rescuedScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_score"] intValue];
data.lastPlayed = (NSString *)[playerLevel objectForKey: #"lastplayed"];
data.dateAdded = (NSString *)[playerLevel objectForKey: #"dateadded"];
data.isNew = ([(NSString *)[playerLevel objectForKey: #"lastplayed"] isEqualToString: #""]);
data.isCompleted = ([(NSNumber *)[playerLevel objectForKey: #"completed"] intValue] == 1);
data.isLocked = NO;
break;
}
j++;
}
if (indexOrder == 1)
{
list = [NSMutableArray arrayWithCapacity: 1];
groupData = [BldgLevelGroupData createObject];
groupData.groupId = groupId;
groupData.firstLevelId = levelId;
groupData.timeLimit = [(NSNumber *)[bldgLevel objectForKey: #"time_limit"] intValue];
groupData.list = list;
// Get SOS items
NSMutableArray *sosItems = [NSMutableArray arrayWithCapacity: 0];
//
NSLog(#"getting levelSOSItems");
NSLog(#"i: %d, j: %d", i, j);
NSLog(#"list: %#", list);
NSLog(#"levelId: %d", levelId);
NSArray *levelSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_LEVEL_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", levelId], #"i", nil]];
NSLog(#"Levelsositems: %#", levelSOSItems);
NSLog(#"getting player sos Items");
NSArray *playerSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i",
nil]];
NSLog(#"playerSoSItems: %#", playerSOSItems);
j = 0;
while (j < [levelSOSItems count])
{
SOSItemData *sosItemData = [SOSItemData createObject];
sosItemData.itemId = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"sos_id"] intValue];
sosItemData.itemName = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"name"];
sosItemData.desc = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"desc"];
sosItemData.coins = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"coins_cost"] intValue];
sosItemData.cash = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"cash_cost"] intValue];
sosItemData.rescuedPtsRequired = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"rescued_required"] intValue];
int k = 0;
while (k < [playerSOSItems count])
{
if ([(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"sos_id"] intValue] == sosItemData.itemId)
{
sosItemData.qty = [(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"qty"] intValue];
break;
}
k++;
}
//NSLog(#"%#", sosItemData);
[sosItems addObject: sosItemData];
j++;
}
groupData.sosItems = sosItems;
[groupsList addObject: groupData];
}
NSLog(#"%#", data);
[list addObject: data];
i++;
}
and here's the code I used to fetch the data from the database:
-(NSArray *) fetchDataFromDatabase:(NSString *)dbPath withQuery: (NSString *)sql withValuesAndTypes: (NSArray *)params
{
/*
dbPath - Name of database file
sql - SQL statement. Prepared statements are allowed to be used here (refer to params
params - Array containing data and its corresponding data type
*/
NSMutableArray *result = nil;
//make sure db is closed
NSLog(#"close database first!");
sqlite3_close(database);
NSLog(#"open database!");
int dbStatus = [self openDatabase: dbPath];
if (dbStatus == SQLITE_OK)
{
//int stmtStatus = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
int stmtStatus = [self prepareStatement: sql withParams: params];
if(stmtStatus == SQLITE_OK)
{
result = [NSMutableArray arrayWithCapacity: 1];
while(sqlite3_step(stmt) == SQLITE_ROW)
{
NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity: 1];
int columnCount = sqlite3_column_count(stmt);
int j = 0;
while (j < columnCount)
{
/*
Possible sqlite data types:
SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL
*/
if (sqlite3_column_type(stmt, j) == SQLITE_INTEGER)
{
[row setObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_FLOAT)
{
[row setObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_TEXT)
{
[row setObject: [NSString stringWithFormat: #"%s", sqlite3_column_text(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_NULL)
{
[row setObject: [NSNull null]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
j++;
}
[result addObject: row];
}
}
else { NSLog(#"stmt error: %d", stmtStatus); }
}
else if (dbStatus == 14)
{
NSLog(#"db error: %d", dbStatus);
NSLog(#"killing app.");
exit(0);
}
else { NSLog(#"db error: %d", dbStatus); }
//Even though the open call failed, close the database connection to release all the memory.
sqlite3_close(database);
return result;
}
sorry if it is wrong..... in your code you didn't finalize statement but useed stmt variable .before close DB ,we should finalize statement if we use statement.....
comment for finalize statement
sqlite3_finalize(Stmt);

Memory Leak in TouchMXL?

I'm using TouchXML to parse an XML-stream the following way:
CXMLDocument *parser = [[CXMLDocument alloc] initWithXMLString:responseString options:0 error:nil];
[responseString release];
// array holding all the nodes
NSArray *directionNodes = [parser nodesForXPath:#"//direction" error:nil];
NSArray *linieNodes = [parser nodesForXPath:#"//route" error:nil];
NSArray *timeNodes = [parser nodesForXPath:#"//time" error:nil];
for (int i = 0; i < [directionNodes count]; i++) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CXMLElement *direction = [directionNodes objectAtIndex:i];
CXMLElement *route = [linieNodes objectAtIndex:i];
CXMLElement *time = [timeNodes objectAtIndex:i];
// if rows are empty, stop it
if ([[direction stringValue] isEqualToString:#""]) {
break;
}
AbfahrtszeitResult *result = [[AbfahrtszeitResult alloc] init];
[result setLinie:[route stringValue]];
[result setZiel:[direction stringValue]];
[result setZeit:[time stringValue]];
[mutableAbfahrten addObject:result];
[result release];
[pool release];
}
Now, I always get a memory leak in the "stringValue"-line... am I doing something wrong or is it TouchXML?
Thanks a lot,
Stefan
-(NSString *) linie {
return linie;
}
- (void) setLinie:(NSString *)textValue {
[textValue retain];
[linie release];
linie = textValue;
}
-(NSString *) ziel {
return ziel;
}
-(void) setZiel:(NSString *)textValue {
[textValue retain];
[ziel release];
ziel = textValue;
}
-(NSString *) zeit {
return zeit;
}
-(void) setZeit:(NSString *)textValue {
[textValue retain];
[zeit release];
zeit = textValue;
}
+ (NSString *) cleanUpString:(NSString *) cleanme {
NSMutableString *tempString = [[NSMutableString alloc] initWithString:cleanme];
[tempString replaceOccurrencesOfString:#" " withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
[tempString replaceOccurrencesOfString:#"&nbsp" withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
return [tempString autorelease];
}
You have at least one leak when [[direction stringValue] isEqualToString:#""] is true as you break out of the for loop without releasing your AutoreleasePool. Beyond that, we'd need to see the implementation of your AbfahrtszeitResult class to see how your Linie setter is defined.