xml and json both giving garbage for language other then english - iphone

here is a sample of my xml file
<TheamName>
<item1>Green</item1>
<item2>Blue</item2>
</TheamName>
<FontName>
<item1>دعاء</item1>
<item2>دعاء</item2>
<item3>دعاء</item3>
<item4>دعاء</item4>
</FontName>
but when i tried to parse this having this response
{
item1 = Green;
item2 = Blue;
},
{
item1 = "\U062f\U0639\U0627\U0621";
item2 = "\U062f\U0639\U0627\U0621";
item3 = "\U062f\U0639\U0627\U0621";
item4 = "\U062f\U0639\U0627\U0621";
}
tried to convert it on json and then tried to have response but have no success it gives the same result for that also.
please show me how to get the original different language string back?
Thakas in advance for the help!
EDIT
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *theXML = [[[NSString alloc] initWithBytes:[arrXmlData mutableBytes] length:[arrXmlData length] encoding:NSUTF8StringEncoding] autorelease];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:[theXML dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] autorelease];
arrSession = [[NSMutableArray alloc] init];
NSArray *nodesLibRateEstimate = [doc nodesForXPath:#"//Headings" error:nil];
for (CXMLElement *node in nodesLibRateEstimate) {
NSMutableDictionary *dictData=[[NSMutableDictionary alloc]init];
for(int counter = 0; counter < [node childCount]; counter++) {
if ([[[node childAtIndex:counter] name] isEqualToString:#"app_name"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"app_name"];
}else if([[[node childAtIndex:counter] name] isEqualToString:#"action_settings"]){
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"action_settings"];
}
}
[arrSession addObject:dictData];
}
NSArray *nodesLibOriginatingServiceCenter = [doc nodesForXPath:#"//TheamName" error:nil];
for (CXMLElement *node in nodesLibOriginatingServiceCenter) {
NSMutableDictionary *dictData=[[NSMutableDictionary alloc]init];
for(int counter = 0; counter < [node childCount]; counter++) {
if ([[[node childAtIndex:counter] name] isEqualToString:#"item1"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item1"];
} else if ([[[node childAtIndex:counter] name] isEqualToString:#"item2"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item2"];
}
}
[arrSession addObject:dictData];
}
NSArray *nodesLibOriginatingServiceCenter2 = [doc nodesForXPath:#"//FontName" error:nil];
for (CXMLElement *node in nodesLibOriginatingServiceCenter2) {
NSMutableDictionary *dictData=[[NSMutableDictionary alloc]init];
for(int counter = 0; counter < [node childCount]; counter++) {
if ([[[node childAtIndex:counter] name] isEqualToString:#"item1"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item1"];
} else if ([[[node childAtIndex:counter] name] isEqualToString:#"item2"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item2"];
} else if ([[[node childAtIndex:counter] name] isEqualToString:#"item3"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item3"];
} else if ([[[node childAtIndex:counter] name] isEqualToString:#"item4"]) {
NSString *strValue;
if ([[[node childAtIndex:counter] stringValue]isEqualToString:#""] || [[node childAtIndex:counter] stringValue]==nil) {
strValue=#"";
}else{
strValue=[self trimString:[[node childAtIndex:counter] stringValue]];
}
[dictData setObject:strValue forKey:#"item4"];
}
}
[arrSession addObject:dictData];
}
NSLog(#"The arrSession is :%#",arrSession);
[connection release];
[arrXmlData release];
}

Your response is right
Instead of printing it in array try to print it individually.
e.g.
NSLog(#"%#", [[arrSession objectAtIndex:1] objectForKey:#"item1"]);
Assuming that your
{
item1 = "\U062f\U0639\U0627\U0621";
item2 = "\U062f\U0639\U0627\U0621";
item3 = "\U062f\U0639\U0627\U0621";
item4 = "\U062f\U0639\U0627\U0621";
}
is at index 1 in arrSession

Related

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

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)")
}
}

objective-c 'double free' error in ARC mode

I'm trying to practice the block and GCD/NSOperation, so I wrote this project Async-objc, but when I'm trying to test it with unit test, I always encountered 'double free' error, I thought there shouldn't be such error in ARC mode.
here is the code
- (void)each:(NSArray *)items iterator:(callbackEach)iterator complete:(callbackWithError)complete {
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
if (!items || items.count == 0) {
complete(nil);
return;
}
callbackWithError __block completeOnce = complete;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(#"start operations %#", queue);
[queue setMaxConcurrentOperationCount:kMaxConcurrentOperationCount];
NSInteger __block count = 0;
for (id item in items) {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
iterator(item, ^(NSError *error) {
if (error) {
completeOnce(error);
completeOnce = nil;
} else {
count++;
if (count >= items.count) {
completeOnce(nil);
completeOnce = nil;
}
}
});
}];
[queue addOperation:op];
}
[queue waitUntilAllOperationsAreFinished];
NSLog(#"all operations are down %#", queue);
}];
[_mainQueue addOperation:blockOp];
}
this is the test code:
- (void)testEachWithBigData {
BOOL __block completed = false;
NSMutableArray *items = [NSMutableArray arrayWithCapacity:100];
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:#"%d", i]];
}
NSMutableArray *result = [NSMutableArray arrayWithCapacity:100];
[_async each:items
iterator:^(id item, callbackWithError callback) {
//NSLog(#"======item %#", item);
NSNumber *num = [NSNumber numberWithInt:[item integerValue]];
//NSLog(#"number %#", num);
[result addObject:num];
callback(nil);
}
complete:^(NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
STAssertNil(error, #"there should be no error");
[result sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *num1 = (NSNumber *)obj1;
NSNumber *num2 = (NSNumber *)obj2;
if ([num1 integerValue] > [num2 integerValue]) {
return NSOrderedDescending;
} else if ([num1 integerValue] < [num2 integerValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSInteger index = 1;
for (NSNumber *num in result) {
STAssertEquals(index, [num integerValue], #"the value should be ordered");
index++;
}
completed = YES;
});
}
];
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:10];
while (!completed && [until timeIntervalSinceNow] > 0) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
}
If you couldn't reproduce the error, increase the test item count to 10000.
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:#"%d", i]];
}
and comment the NSLog()
then Command + U to run the unit test
here is the error message:
otest(11105,0xb039f000) malloc: * error for object 0xa0f8000: pointer being freed was not allocated
otest(11209,0xb0115000) malloc: * error for object 0x41dcc00: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
I cannot reproduce the 'double free' error this time

Memory leak while parsing XML using TouchXML

I am using TouchXML to parse XML. While i am running the same in "Profile" Mode. I can able to see the memory leak. How can I fix this issue?
-(NSMutableArray *) grabXML:(NSData *)xmlData andQuery:(NSString *)query {
NSMutableArray *blogEntries = [[[NSMutableArray alloc] init] autorelease];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithData:xmlData options:0 error:nil] autorelease];
NSArray *resultNodes = [rssParser nodesForXPath:query error:nil];
for (CXMLElement *resultElement in resultNodes) {
NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [resultElement childCount]; counter++) {
[blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
}
for( int i = 0; i < [[resultElement attributes] count]; i++) {
CXMLNode *node = [[resultElement attributes] objectAtIndex:i];
[blogItem setObject:[[resultElement attributeForName:[node name]] stringValue] forKey:[node name]];
}
[blogEntries addObject:[blogItem copy]];
[blogItem release];
}
return [blogEntries copy];
}
I am calling the above method in the below mentioned format.
NSMutableArray *arr = [[self grabXML:responseData andQuery:#"//wsCheneliereResult"] autorelease];
[blogEntries addObject:[blogItem copy]];
Here is your mistake : you do not need to copy the blogItem, addObject: will actually retain its argument so that you can safely call [blogItem release]; afterward.
And you most probably should not do return [blogEntries copy] either, and return just blogEntries : this is common programming habit that methods whose name does not contain 'copy' or 'create' return autoreleased values, such as you do not need to release them when you are done with them.
To sum up, I would go with :
-(NSMutableArray *) grabXML:(NSData *)xmlData andQuery:(NSString *)query {
NSMutableArray *blogEntries = [[[NSMutableArray alloc] init] autorelease];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithData:xmlData options:0 error:nil] autorelease];
NSArray *resultNodes = [rssParser nodesForXPath:query error:nil];
for (CXMLElement *resultElement in resultNodes) {
NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [resultElement childCount]; counter++) {
[blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
}
for( int i = 0; i < [[resultElement attributes] count]; i++) {
CXMLNode *node = [[resultElement attributes] objectAtIndex:i];
[blogItem setObject:[[resultElement attributeForName:[node name]] stringValue] forKey:[node name]];
}
[blogEntries addObject:blogItem];
[blogItem release];
}
return blogEntries;
}
and
NSMutableArray *arr = [self grabXML:responseData andQuery:#"//wsCheneliereResult"];

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);

TouchXML to read in twitter feed for iphone app

So I've managed to get the feed from twitter and am attempting to parse it...
I only require the following fields from the feed:
name, description, time_zone and created_at
I am successfully pulling out name and description.. however time_zone and created_at always are nil... The following is the code...
Anyone see why this might not be working?
-(void) friends_timeline_callback:(NSData *)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Data from twitter: %#", string);
NSMutableArray *res = [[NSMutableArray alloc] init];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:data options:0 error:nil] autorelease];
NSArray *nodes = nil;
//! searching for item nodes
nodes = [doc nodesForXPath:#"/statuses/status/user" error:nil];
for (CXMLElement *node in nodes)
{
int counter;
Contact *contact = [[Contact alloc] init];
for (counter = 0; counter < [node childCount]; counter++)
{
//pulling out name and description only for the minute!!!
if ([[[node childAtIndex:counter] name] isEqual:#"name"]){
contact.name = [[node childAtIndex:counter] stringValue];
}else if ([[[node childAtIndex:counter] name] isEqual:#"description"]) {
// common procedure: dictionary with keys/values from XML node
if ([[node childAtIndex:counter] stringValue] == NULL){
contact.nextAction = #"No description";
}else{
contact.nextAction = [[node childAtIndex:counter] stringValue];
}
}else if ([[[node childAtIndex:counter] name] isEqual:#"created_at"]){
contact.date == [[node childAtIndex:counter] stringValue];
}else if([[[node childAtIndex:counter] name] isEqual:#"time_zone"]){
contact.status == [[node childAtIndex:counter] stringValue];
[res addObject:contact];
[contact release];
}
}
}
self.contactsArray = res;
[res release];
[self.tableView reloadData];
}
Thanks in advance for your help!!
Fiona
Might be a mistake but why are they double equals (==), usually used for a condition check