Since some months I am interested in coding. At the moment I am working on a programm which saves informations from textfields in a sqlite3 database. I am programming this project on Objective C in Xcode for Mac. Unfortunately I have problems in inserting data into my database. When I insert it and open my database in Terminal I just get this information in the cell for the string:
Here ist my code:
NSString *Bt = [NSString stringWithFormat:#"%#", Text]; //Theres a IBOutlet NSTextField *Text; in the Header data of the class
dbPath=#"/Users/Desktop/database.db";
if (sqlite3_open([dbPath UTF8String], &database)!=SQLITE_OK) {
sqlite3_close(database);
NSLog(#"Failed to open database");
} else {
char *errorMessage;
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO table (table) VALUES (\"%#\")", Bt];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_exec(database, insert_stmt, NULL, NULL, &errorMessage)==SQLITE_OK){
NSLog(#"Data inserted");
[db_status setFloatValue:5];
}
}
}
It would be great if somebody can help me. I think it is just a small error but I don´t get the problem ;(
Best regards,
Robby
by the looks of your IBOUTLET connection, how you have your code, Bt is equal to the TextField. But what you want is the text value in the TextField. so you would use this: NSString *Bt = [NSString stringWithFormat:#"%#", Text.stringValue]; NSTextField has a property named stringValue and this will return the NSString that contains the value inside the textfield, Text.
Allowing Quotation Marks in Your Database
So easiest way, i can think of, is having a category method on NSString. So wherever you're going to save string or text from the user to your database, you would use this function to then insert into your format statement. and example shown below:
Header File of NSString Category
#interface NSString (STRING_)
/**
* Allowing Qoutation marks inside a string to be saved in a SQL column with the string format sourrounded by #"\"%#\"". this will not modify the string, only return a modified copy
* #return NSString *
*/
- (NSString *)reformatForSQLQuries;
#end
Implantation File of NSString Category
#implementation NSString (STRING_)
- (NSString *)reformatForSQLQuries {
NSString *string = self;
//Depending on how you "wrap" your strings to format the string values into your INSERT, UPDATE, or DELETE queries, you'll only have to use one of these statements. YOU DO NOT NEED BOTH
//Use this if you have your format as: '%#'
string = [string stringByReplacingOccurrencesOfString: #"'" withString: #"''"];
//Use this if you have your format as: \"%#\"
string = [string stringByReplacingOccurrencesOfString: #"\"" withString: #"\"\""];
return string;
}
example
...
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO table (table) VALUES (\"%#\")", [Bt reformatForSQLQuries]];
...
I got the solution ! It´s false to write:
NSString *Bt = [NSString stringWithFormat:#"%#", Text];
The solution is to get the value from the NSTextField:
NSString *Bt = [NSTextField stringValue];
What I still don´t understand is why it´s not possible to save Strings which include this symbol: "". For example:
The database saves this: I like programming.
But not this: I like "programming".
Can somebody explain me why ?
Related
Get username values from sqlite db.
-(NSArray*)getUname
{
NSArray *resul = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSArray *fetchedRecords = [resul valueForKey:#"uName"];
}
Insert this array values into NSPopupButton
[_registeredUserPopupButton addItemsWithTitles:[self getUname]];
Get a string value from NSPopupButton dropdown list
NSString *usrNam = [NSString stringWithFormat:#"%#",[_registeredUserPopupButton selectedItem]];
From the above code usrNam value returns like below
"NSMenuItem: 0x6080000a9c00 mickel"
but i want my nsstring output as "mickel"
Just get the title from the menu item:
NSString *usrNam = [[_registeredUserPopupButton selectedItem] title];
or with dot notation
NSString *usrNam = _registeredUserPopupButton.selectedItem.title;
The -selectedItem method returns a NSMenuItem object. This in turn has a title property which is what I think you are looking for. Should be as below I think.
NSString *usrNam = [NSString stringWithFormat:#"%#",[_registeredUserPopupButton selectedItem.title]];
I need my user to enter numbers to type his telephone number.The user can only enter 8 numbers(for eg. XXXXXXXX). I need to change the phone number to be in the format XX-XX-XXXX.
This is what I have tried:
[tfDID.text insertString:#"-" atIndex:2];
[tfDID.text insertString:#"-" atIndex:5];
But it is returning me an error saying:
No Visible #interface for 'NSString' declares the selector 'insertString:atIndex:'
Need some guidance on this. Sorry if this is a stupid question.
No Visible #interface for 'NSString' declares the selector 'insertString:atIndex:'
As you are trying to mutate the textbox's value, which returns you NSString.
NSString object can not be mutated, so convert it into a mutable string then manupulate it.
Make your string NSMutableString.
As,
NSMutableString *tfDIDString=[NSMutableString stringWithString:tfDID.text];
[tfDIDString insertString:#"-" atIndex:2];
[tfDIDString insertString:#"-" atIndex:5];
[UITextField text] is NSString, you need to declare local variable of NSMutableString and perform insertString operations on it
Hope it helps you
Implement <UITextFieldDelegate> and then do:
-(void)textFieldDidChange:(UITextField*)textField
{
if( textField.text.length == 2 || textField.text.length == 5 ){
textField.text = [textField.text stringByAppendingString:#"-"];
}
}
Completely agree with the answer suggesting making it a mutable string.
Just to play devils advocate you could do:
NSString *partOne = [NSString stringWithRange:NSMakeRange(0,2)];
NSString *partTwo = [NSString stringWithRange:NSMakeRange(2,2)];
NSString *partThree = [NSString stringWithRange:NSMakeRange(4,4)];
NSString *formattedNumber = [NSString stringWithFormat:#"%#-%#-%#",partOne,partTwo,partThree];
I've written it out longhand but you could compress the string declarations for the parts in to the stringWithFormat call if you don't mind nesting and sacrifcing a bit of readability.
I want to set a variable value. But I don't know how to. I want replace 3456 with "value".
Code:
NSString *value = textbox.text;
NSString *field = [captcha stringByEvaluatingJavaScriptFromString:#"document.getElementById('mainPagePart:rn3').value='3456';"];
I think what you're trying to say is you want to put the contents of value into the string?
NSString *field = [captcha stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"document.getElementById('mainPagePart:rn3').value='%#';", value]];
How do you check if an NSString begins with a certain character (the character *).
The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.
You can use the -hasPrefix: method of NSString:
Objective-C:
NSString* output = nil;
if([string hasPrefix:#"*"]) {
output = [string substringFromIndex:1];
}
Swift:
var output:String?
if string.hasPrefix("*") {
output = string.substringFromIndex(string.startIndex.advancedBy(1))
}
You can use:
NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:#"*"] ) {
newString = [myString substringFromIndex:1];
}
hasPrefix works especially well.
for example if you were looking for a http url in a NSString, you would use componentsSeparatedByString to create an NSArray and the iterate the array using hasPrefix to find the elements that begin with http.
NSArray *allStringsArray =
[myStringThatHasHttpUrls componentsSeparatedByString:#" "]
for (id myArrayElement in allStringsArray) {
NSString *theString = [myArrayElement description];
if ([theString hasPrefix:#"http"]) {
NSLog(#"The URL is %#", [myArrayElement description]);
}
}
hasPrefix returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
- (BOOL)hasPrefix:(NSString *)aString,
parameter aString is a string that you are looking for
Return Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.
As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.
NSString* myString = #"10:Username taken";
if([myString hasPrefix:#"10"]) {
//display more elegant error message
}
Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.
NSString *stringWithoutAsterisk(NSString *string) {
NSRange asterisk = [string rangeOfString:#"*"];
return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:#"http"]) {
//starts with http
}
This might help? :)
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/characterAtIndex:
Just search for the character at index 0 and compare it against the value you're looking for!
This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:
NSString = [yourString stringByReplacingOccurrencesOfString:#"YOUR CHARACTERS YOU WANT TO REMOVE" withString:#"CAN either be EMPTY or WITH TEXT REPLACEMENT"];
This is how I use it:
//declare what to look for
NSString * suffixTorRemove = #"</p>";
NSString * prefixToRemove = #"<p>";
NSString * randomCharacter = #"</strong>";
NSString * moreRandom = #"<strong>";
NSString * makeAndSign = #"&";
//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:#"&"];
//check the output
NSLog(#"returnStr IS NOW: %#", returnStr);
This one line is super easy to perform three actions in one:
Checks your string for the character/s you do not want
Can replaces them with whatever you like
Does not affect surrounding code
NSString* expectedString = nil;
if([givenString hasPrefix:#"*"])
{
expectedString = [givenString substringFromIndex:1];
}
I want to compare the value of an NSString to the string "Wrong". Here is my code:
NSString *wrongTxt = [[NSString alloc] initWithFormat:#"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
doSomething;
}
Do I really have to create an NSString for "Wrong"?
Also, can I compare the value of a UILabel's text to a string without assigning the label value to a string?
Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:#"Wrong"]){
//doSomething;
}
Using #"" simply creates a string literal, which is a valid NSString.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}
if ([statusString isEqualToString:#"Wrong"]) {
// do something
}
Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:#"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "#" symbol in a much more convenient way:
NSString *myString = #"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!
You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:#"abc"];
NSString *myString = [NSString stringWithFormat:#"abc %d efg", 42];