EXC_BAD_ACCESS error - xcode

I have an application concists of uitextview (self.animalDesciption) , and button
I use the button to update database with the text in the uitextview
but it always give EXC_BAD_ACCESS at the line
NSString *NewData = [NSString stringWithFormat:#"%#%#%#%#", #"Update animals set description = ",TheNewText , " Where name = ",the_user];
the full code is
sqlite3 *database;
// Setup some globals
NSString *databaseName = #"test.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString * databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[databasePath retain];
sqlite3_stmt *compiledStatement;
NSString * TheNewText = self.animalDesciption.text;
[TheNewText retain];
NSString * the_user = AnimalName ;
[ the_user retain];
NSString *NewData = [NSString stringWithFormat:#"%#%#%#%#", #"Update animals set description = ",TheNewText , " Where name = ",the_user];
[NewData retain] ;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = [NewData UTF8String];
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)== SQLITE_OK) {
sqlite3_reset(sqlStatement);
}
any suggestion please
Best regards

You are missing a "#" before the string " Where name = ".
Try:
NSString *NewData = [NSString stringWithFormat:#"%#%#%#%#", #"Update animals set description = ",TheNewText , #" Where name = ",the_user];

Try:
NSString *NewData = [NSString stringWithFormat:#"%#%#%#%#", #"Update animals set description = ",TheNewText , #" Where name = ",the_user];
Note the #"Where name = "

Related

Create PLIST with document path of each file in selected folder

I have a folder called 'thepdfpowerpoints'. I simply want to at launch, create a PLIST file that will create an entry for each PDF in the folder showing the path to that particular file. I have the following set up, and it puts the right number of entries, but each entry is the same path listed 399 times.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mastersonglist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"mastersonglist.plist"] ];
}
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
}
else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
NSBundle *bundle = [NSBundle mainBundle];
self.files = [bundle pathsForResourcesOfType:#"pdf" inDirectory:#"thepdfpowerpoints"];
NSMutableArray *names = [NSMutableArray arrayWithCapacity:[self.files count]];
for (NSString *pathoffile in self.files) {
pathoffile = [self.files objectAtIndex:thepath.row];
[names addObject:pathoffile];
}
for (NSString *test in names) {
test = [self.files objectAtIndex:thepath.row];
[data setObject:names forKey:#"thename"];
[data writeToFile:path atomically:YES];
}

How to pass Windows Azure Marketplace Account Key in an NSURLSession?

I have been successfully executing Image queries on "Google Search" with the following code:
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:#"&+=?"];
NSString * escapedValue = [searchKeys stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * urlString = [[NSString alloc] initWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#", escapedValue];
NSURL *JSONURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *googleResult = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
// PROCESS GOOGLE RESULTS HERE...
}];
[dataTask resume];
... until Google decided to restrict the access.
Now, I would like to implement the same with Microsoft Bing! (Windows Azure Marketplace).
I have obtained the Account Key (to get 5000 free searches per month).
I understand that I have to pass the Account Key as part of the request.
How can I change my code to implement this ?
If it is GET request you can just add another query at the end of the URL string but if it is POST request you can use
NSString *constructedParam = #"key=value&key=value";
NSData *parameterData = [constructedParam dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request addValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:parameterData]
Thanks. I was able to solve the issue after reading some documentation from Microsoft. This is the required code:
// Method required to encode data...
-(NSString *)stringByEncodingInBase64:(NSData *)data
{
NSUInteger length = [data length];
NSMutableData *mutableData = [[NSMutableData alloc] initWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3)
{
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++)
{
value <<= 8;
if (j < length)
{
value |= (0xFF & input[j]);
}
}
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
NSUInteger idx = (i / 3) * 4;
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
The following is the code to get the search result:
NSData *authData;
NSString *authKey = #"<ENTER Windows Azure Marketplace Account KEY HERE>";
NSLog (#"authkey:%#",authKey);
authData = [[[NSString alloc] initWithFormat:#"%#:%#", authKey, authKey] dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [[NSString alloc] initWithFormat:#"Basic %#", [self stringByEncodingInBase64:authData]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setHTTPAdditionalHeaders:#{#"Authorization": authValue}];
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:#"&+=?"]; // %26, %3D, %3F
NSString * escapedValue = [<ENTER SEARCH CRITERIA HERE> stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * urlString = [[NSString alloc] initWithFormat:#"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='%#'&$top=50&$format=json", escapedValue];
NSURL *JSONURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSessionDataTask * dataTask = [[NSURLSession sessionWithConfiguration:config] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data == nil){
// Process failure here.
}
NSDictionary *resultadoCompleto = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
// PROCESS BING! RESULTS HERE...
}];
[dataTask resume];
resultadoCompleto shows the complete results!

NSManagedObject : having one answer of a loop instead of multiple answer from a loop Xcode

i have a problem when creating a txt file from a for statement. Here is the code of the statement on a CoreData.
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * allTickets = [[NSFetchRequest alloc] init];
[allTickets setEntity:[NSEntityDescription entityForName:#"Place" inManagedObjectContext:context]];
[allTickets setIncludesPropertyValues:NO];
NSError * error = nil;
NSArray * ticks = [context executeFetchRequest:allTickets error:&error];
for (NSManagedObject * tick in ticks) {
NSArray *keys = [[[tick entity] attributesByName] allKeys];
NSDictionary *myDict = [tick dictionaryWithValuesForKeys:keys];
NSString *theDate = [myDict objectForKey:#"date"];
NSString *theName = [myDict objectForKey:#"name"];
NSString *theNumber = [myDict objectForKey:#"number"];
NSString * finalExport = [NSString stringWithFormat:#"%#%#%#", theDate, theName, theNumber];
NSLog(#"%#",finalExport);
the NSLog result print out all the entries in CoreData correctly, running each request one after the other.
My problem is that when i want to create a txt with the finalExport NSString, i only have the first request in the file.
For exemple i got an NSLog with :
01.01.2015 MYNAME 34555445
02.01.2015 MYNAME 34523445
03.01.2015 MYNAME 34115445
04.01.2015 MYNAME 34552345
But in the text file i only got
01.01.2015 MYNAME 34555445
So how can i have a text file with all the NSLog Results
Thanks in advance for your help ;)
EDIT ++++++++++++++
Here is the rest of the code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [finalExport writeToFile:[documentsDirectory stringByAppendingPathComponent:#"Number.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
NSLog(#"NOT WORKING");
}
You need to make sure you write an array of entries to the file, not just one entry.

Cocoa check for multiple file extensions in folder

I need to raise an Alert panel if a folder does not contain files with the extension strings in code below. The "input" textField contains the path string ... Can't get it to work ... Thanks for help.
NSString * filePath = [input stringValue];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSString *theFolder= [fileURL path];
NSFileManager * fileMan = [[NSFileManager alloc] init];
NSArray * files = [fileMan contentsOfDirectoryAtPath:theFolder error:nil];
if (files)
{
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
if (!([file.pathExtension isEqualToString:#"txt"] || [file.pathExtension isEqualToString:#"rtf"] || [file.pathExtension isEqualToString:#"doc"] || [file.pathExtension isEqualToString:#"rtfd"])) {
///alert code
Replace
NSFileManager * fileMan = [[NSFileManager alloc] init];
with
NSFileManager * fileMan = [[NSFileManager defaultManager];
Make sure that
NSString *theFolder= [fileURL path];
gives you a folder and not a filename!
I would recommend to lowercase all strings in the comparison.
Declare a bool variable outside the for loop like
BOOL otherFiles = NO;
if (files) {
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
if (!([file.pathExtension.lowercaseString isEqualToString:#"txt"] ||
[file.pathExtension.lowercaseString isEqualToString:#"rtf"] ||
[file.pathExtension.lowercaseString isEqualToString:#"doc"] ||
[file.pathExtension.lowercaseString isEqualToString:#"rtfd"])
) otherFiles = YES;
}
if (otherFiles) NSRunAlertPanel.....
Make sure that files contains what you expect!

naming a number of NSButtons

I have written some terrible code but it works. Is there a better way to write this? _decade.x are NSButtons.
int baseDecade = 1940;
NSString *title;
int currentDecade = 0;
- (IBAction)nameDecade:(id)sender {
currentDecade = baseDecade;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade1.stringValue = title;
currentDecade = currentDecade +10;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade2.stringValue = title;
currentDecade = currentDecade +10;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade3.stringValue = title;
In iOS you can put your buttons in a single IBOutletCollection in interface builder, or in an NSArray if you create your buttons through code. With that outlet collection / array in hand, you can use a loop to reference _decadeN by their index in the collection:
#property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *decadeButtons;
...
for (int i = 0 ; i != decadeButtons.count ; i++) {
UIButton * decade = decadeButtons[i];
NSString *title = [NSString stringWithFormat: #"%ld", (long)(baseDecade+10*i)];
decade.stringValue = title;
}
Edit: OSX does not support IBOutletCollections yet, so you would need to put _decadeN buttons in an array namually:
// I am using the new array literal syntax; using arrayWithObjects will work too.
NSArray *decadeButtons = #[_decade1, _decade2, _decade3];
// Use the same loop as above:
for (int i = 0 ; i != decadeButtons.count ; i++) {
UIButton * decade = decadeButtons[i];
NSString *title = [NSString stringWithFormat: #"%ld", (long)(baseDecade+10*i)];
decade.stringValue = title;
}

Resources