The method below runs against a sqlite3 database. It's intended to fetch all of the primary keys for records matching each of the foreign keys in the array it's passed as a parameter (flds).
- (NSArray*) columnPrimaryKeysForFields:(NSArray*)flds
{
NSMutableArray* retval = [[NSMutableArray alloc] init];
NSString* query = #"SELECT ID FROM Pages WHERE FieldID = ? ORDER BY ID";
sqlite3_stmt* statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
for (NSNumber* fieldID in flds)
{
sqlite3_bind_int64(statement, 1, (int)[fieldID longValue]);
while (sqlite3_step(statement) == SQLITE_ROW)
{
[retval addObject:[NSNumber numberWithInteger:sqlite3_column_int(statement, 0)]];
}
}
sqlite3_finalize(statement);
}
else
{
NSLog(#"SQL PREPARE columnPrimaryKeysForFields failed");
}
return [NSArray arrayWithArray:retval];
}
In the database, there are multiple records containing each of the keys in flds. When the method executes it fetches all of the records containing first key in flds, but only the first record containing each of the subsequent keys in flds. I can't figure out why the first key in flds fetches the correct number of records but the subsequent keys do not.
Thanks in advance for your help!
You have to call sqlite3_reset after the last step call.
Related
I was looking for a way to create a window like that one in my program, but I haven't found any implementation of that. All I can do for now is get all certificates from keychain, but I can't get a cert in pem or der format. It is needed to supply certificate to a particular site.
- (void)logMessageForStatus:(OSStatus)status
functionName:(NSString *)functionName
{
CFStringRef errorMessage;
errorMessage = SecCopyErrorMessageString(status, NULL);
NSLog(#"error after %#: %#", functionName, (__bridge NSString *)errorMessage);
CFRelease(errorMessage);
}
- (void)listCertificates
{
OSStatus status;
SecKeychainSearchRef search = NULL;
// The first argument being NULL indicates the user's current keychain list
status = SecKeychainSearchCreateFromAttributes(NULL,
kSecCertificateItemClass, NULL, &search);
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecKeychainSearchCreateFromAttributes()"];
return;
}
SecKeychainItemRef searchItem = NULL;
while (SecKeychainSearchCopyNext(search, &searchItem) != errSecItemNotFound) {
SecKeychainAttributeList attrList;
CSSM_DATA certData;
attrList.count = 0;
attrList.attr = NULL;
status = SecKeychainItemCopyContent(searchItem, NULL, &attrList,
(UInt32 *)(&certData.Length),
(void **)(&certData.Data));
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecKeychainItemCopyContent()"];
CFRelease(searchItem);
continue;
}
// At this point you should have a valid CSSM_DATA structure
// representing the certificate
SecCertificateRef certificate;
status = SecCertificateCreateFromData(&certData, CSSM_CERT_X_509v3,
CSSM_CERT_ENCODING_BER, &certificate);
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecCertificateCreateFromData()"];
SecKeychainItemFreeContent(&attrList, certData.Data);
CFRelease(searchItem);
continue;
}
// Do whatever you want to do with the certificate
// For instance, print its common name (if there's one)
CFStringRef commonName = NULL;
CFErrorRef err = NULL;
///CFArrayRef arr = NULL;
SecCertificateCopyCommonName(certificate, &commonName);
certs = SecCertificateCopyValues(certificate, NULL, &err);
//NSLog(#"common name = %#", (__bridge NSString *)commonName);
//NSLog(#"data = %#", (__bridge NSArray *)arr);
//certs = arr;
if (commonName) CFRelease(commonName);
//if (arr) CFRelease(arr);
SecKeychainItemFreeContent(&attrList, certData.Data);
CFRelease(searchItem);
}
CFRelease(search);
}
example
Is there any standard api to call such window? Or maybe there is some library? And how can I get der data from SecCertificateRef.
Thank you in advance!
I have an NSArray loaded with objects (see below). I need to load these into a tableview based on which indexpath.row is clicked from another tableview.
If a user selects indexpath.row = 0, then the second tableview is reloaded with ORDER_CODE's which contain only GROUP = 0.
If the user selects indexpath.row = 1, then the second tableview is reloaded with ORDER_CODE's which contain only GROUP = 1.
Anyone have any advice/coding on how I can search thru the array and display the relevant data into the second tableview?
array=(
{
GROUP = 0;
"ORDER_CODE" = 410;
"PROD_DESCR" = "cement";
id = 0;
},
{
GROUP = 0;
"ORDER_CODE" = 411;
"PROD_DESCR" = "concrete";
id = 1;
},
{
GROUP = 1;
"ORDER_CODE" = 405;
"PROD_DESCR" = "asphalt";
id = 2;
})
Try the following code to filter the results (on clicking a particular tablerow) from the given array
NSArray *array; //your data array
//create a search predicate to filter the array
NSPredicate *searchPredicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
BOOL isValidGroup = [evaluatedObject[#"GROUP"] integerValue] == indexPath.row;
return isValidGroup;
}];
NSArray *filteredArray = [array filteredArrayUsingPredicate:searchPredicate]; //this is the filtered array you can use for the displaying in the table
i am writing the code below manner.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions error:&error];
NSLog(#"%#",json);
The printed dictionary is
(
{
Contents = (
{
Id = 2;
LastUpdated = "/Date(1338048712847+0000)/";
Title = "Webinar: HP & MS solutions for Mid-Market";
Url = "http://infra2apps.blob.core.windows.net/content/VMMM019-HP-MS_MidMarket.wmv";
},
{
Id = 1;
LastUpdated = "/Date(1338048712773+0000)/";
Title = "Webinar: Private Cloud with HP & MS";
Url = "http://infra2apps.blob.core.windows.net/content/VMPC012-HPMS_PrivateCloud.wmv";
}
);
Id = 1;
ImageUrl = "http://infra2apps.blob.core.windows.net/eventapp/black-microsoft-logo.jpg";
Name = "Unified Communications & Collaborations";
Sessions = (
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275822000000+0000)/";
FriendlyName = TB3257;
Id = 1;
Location = "Building N-4105";
Speakers = (
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275818400000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync";
},
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275825600000+0000)/";
FriendlyName = TB3258;
Id = 2;
Location = "Building N-4105";
Speakers = (
{
Company = HP;
Email = "janedoe#hp.com";
Name = "Jane Doe";
Title = "Vice President";
},
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275822000000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync - Part 2";
}
);
},
....etc
And then store the content values into another dictionary after that i store into an array.
the below code is to store the array id
NSDictionary *boothmenucontents = [json valueForKey: #"Contents"];
NSMutableArray *dictResponseboothmenucontentsArray = [[NSMutableArray alloc] initWithObjects: boothmenucontents,nil];
for(int i = 0; i<[dictResponseboothmenucontentsArray count]; i++)
{
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
NSLog(#"id array is %#",IdArrayboothmenucontentes);
for(int k=0;k<[IdArrayboothmenucontentes count];k++)
{
NSString * strcontentId= [NSString stringWithFormat:#"%#",[IdArrayboothmenucontentes objectAtIndex:k]];
NSLog(#"strcontentId%#",strcontentId);
label.text=strcontentId;
[boothmenuidarrayvalues addObject:strcontentId];
NSLog(#"%#",boothmenuidarrayvalues);
}
}
finally i print the boothmenuidarrayvalues
it print like this
"(\n 2,\n 1\n)",
"(\n 4,\n 3\n)",
"(\n 6,\n 5\n)",
"(\n 8,\n 7\n)",
"(\n 10,\n 9\n)",
"(\n 12,\n 11\n)"
but i want to print content id only once but it print in a row in two times.
May be i follow a wrong method please tell me how to give own root for that response.
Please help me.......
Perhaps It will help you.
NSMutableArray *contenstsArray = [contentsDictionary ValueForKey:#"Contents"]; //Suppose you already brought all the json data into contentsDictionary
NSMutableArray *idArray = [[NSMutableArray alloc] init];
for(NSMutableDictionary *idDic in contenstsArray) {
NSString *idString = [idDic valueForKey:#"Id"];
[idArray addObject:];
}
This line looks wrong:
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
I'm not sure what you are expecting it to do, but what it looks like it does is grab the ith object in the dictResponseboothmenucontentsArray, which is a dictionary and then gets the object in that dictionary with the key "Id", which is an number, so IdArrayboothmenucontentes now contains an NSNumber, not an array.
I manage to get Json for my server and parse in Xcode , I can then convert Json to a object and loaded my uitableview, the problems is my Json have 7 objects ..
you can see the full Json here
2012-05-05 10:45:02.727 passingdata[63856:fb03] array : {
posts = {
Friday = (
{
GymClass = {
"CLASS-TYPE2" = "";
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Friday;
TIME = "13:00 - 14:30";
};
}
);
Monday = (
{
GymClass = {
"CLASS-TYPE2" = "Fighters Training";
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Muay Thai ";
"DAY_OF_WEEK" = Monday;
TIME = "09:30 - 11:00";
};
}, ......
with this code I can get friday's "Friday" and display the GymClass info "GymClass" on my table
- (void)fetchedData:(NSData *)responseData { //parse out the json data
searchResults2 = [NSMutableArray arrayWithCapacity:10];
NSError* error;
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
if (array == nil) {
NSLog(#"Expected 'posts' array");
return;
}
for (NSDictionary *resultDict in array)
{
SearchResult *searchResult3;
searchResult3 = [self parseTrack:resultDict];
if (searchResult3 != nil) {
[searchResults2 addObject:searchResult3];
}
}
[self.tableView reloadData];
}
- (SearchResult *)parseTrack:(NSDictionary *)dictionary
{
SearchResult *searchResult1 = [[SearchResult alloc] init];
searchResult1.classType= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_TYPE"];
searchResult1.classLevel= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_LEVEL"];
NSLog(#"parse track = %#", searchResult1);
return searchResult1;
}
I can get the elements for one day but how do I get the Elements for every day (Mon,Tue...Sun)so i can display on my table by sections?
thanks for your help..
Well in your code, you already are doing that:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
Wen can start from there to retrieve only the object posts:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *posts = [dictionary objectForKey:#"posts"];
//Iterate over posts
for (NSArray *aDay in posts){
//Do something
NSLog(#"Array: %#", aDay);
}
Here, i am using Fast Enumeration to iterate over the dictionary, you should check this here.
In my cocoa application I am maintaining a SQLite db within resources folder and trying to do some select, delete operations in it but after some time it starts giving me 'Database is locked' error.
The methods which I am using for select delete operations are as follows:
// method to retrieve data
if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, #"Failed to open database");
}
NSLog(#"mailBodyFor:%d andFlag:%d andFlag:%#",UId,x,Ffolder);
NSMutableArray *recordsToReturn = [[NSMutableArray alloc] initWithCapacity:2];
NSString *tempMsg;
const char *sqlStatementNew;
NSLog(#"before switch");
switch (x) {
case 9:
// tempMsg=[NSString stringWithFormat:#"SELECT * FROM users_messages"];
tempMsg=[NSString stringWithFormat:#"SELECT message,AttachFileOriName as oriFileName,AttachmentFileName as fileName FROM users_messages WHERE id = (select message_id from users_messages_status where id= '%d')",UId];
NSLog(#"mail body query - %#",tempMsg);
break;
default:
break;
}
sqlStatementNew = [tempMsg cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *compiledStatementNew;
NSLog(#"before if statement");
if(sqlite3_prepare_v2(database, sqlStatementNew, -1, &compiledStatementNew, NULL) == SQLITE_OK) {
NSLog(#"the sql is finalized");
while(sqlite3_step(compiledStatementNew) == SQLITE_ROW) {
NSMutableDictionary *recordDict = [[NSMutableDictionary alloc] initWithCapacity:3];
NSString *message;
if((char *)sqlite3_column_text(compiledStatementNew, 0)){
message = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatementNew, 0)];
}
else{
message = #"";
}
NSLog(#"message - %#",message);
NSString *oriFileName;
if((char *)sqlite3_column_text(compiledStatementNew, 1)){
oriFileName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatementNew, 1)];
}
else{
oriFileName = #"";
}
NSLog(#"oriFileName - %#",oriFileName);
NSString *fileName;
if((char *)sqlite3_column_text(compiledStatementNew, 2)){
fileName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatementNew, 2)];
}
else{
fileName = #"";
}
NSLog(#"fileName - %#",fileName);
[recordDict setObject:message forKey:#"message"];
[recordDict setObject:oriFileName forKey:#"oriFileName"];
[recordDict setObject:fileName forKey:#"fileName"];
[recordsToReturn addObject:recordDict];
[recordDict release];
}
sqlite3_finalize(compiledStatementNew);
sqlite3_close(database);
NSLog(#"user messages return -%#",recordsToReturn);
return recordsToReturn;
}
else{
NSLog(#"Error while creating retrieving mailBodyFor in messaging '%s'", sqlite3_errmsg(database));
sqlite3_close(database);
}
// method to delete data
if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, #"Failed to open database");
}
NSString *deleteQuery = [[NSString alloc] initWithFormat:#"delete from users_messages_status where id IN(%#)",ids];
NSLog(#"users_messages_status msg deleteQuery - %#",deleteQuery);
sqlite3_stmt *deleteStmnt;
const char *sql = [deleteQuery cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, sql, -1, &deleteStmnt, NULL) != SQLITE_OK){
NSLog(#"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
}
else{
NSLog(#"successful deletion from users_messages");
}
if(SQLITE_DONE != sqlite3_step(deleteStmnt)){
NSLog(#"Error while deleting. '%s'", sqlite3_errmsg(database));
}
sqlite3_close(database);
Things are going wrong in this sequence
Data is retrieved
'Database is locked' error arises on performing delete operation.
When I retry to perform 1st step.. it now gives same error.
Can anyone suggest me:
If I am doing anything wrong or missing some check?
Is there any way to unlock it when it gives locked error?
Thanks,
Miraaj
It is really uncommon that open/close the database every time you access.
If it is your intended scenario, it would be much better to use a normal file.
Open the database at startup and close at exit. This could solve all your problems.