I am pulling out some language sentences (in different languages) and displaying them in TableView (max 5 rows each row) and when user taps on any row, then I navigate user to a new screen and display full text there.
The problem that i am running into is, it is taking too much time to convert the characters to be visible properly on device.
I wrote the following code to convert the json text for each row:
NSString *msgDesc = [myContentsArray objectAtIndex:indexPath.row];
char const *cStr = [msgDesc cStringUsingEncoding:NSISOLatin1StringEncoding];
msgDesc = [NSString stringWithCString: cStr encoding:NSUTF8StringEncoding];
Thanks for the help.
Regards,
Reno Jones
Since conversion is taking too long, you should move it out from your tableView:cellForRowAtIndexPath: method into the code that pulls the data out from its data source, do the conversion there, and store it for future use.
Add NSMutableArray *myContentsArrayConverted to your class, then convert everything into it, and use in your tableView:cellForRowAtIndexPath: instead of performing the conversion each time you must display your string:
for (int i = 0 ; i != myContentsArray.count ; i++) {
NSString *msgDesc = [myContentsArray objectAtIndex:i];
char const *cStr = [msgDesc cStringUsingEncoding:NSISOLatin1StringEncoding];
[myContentsArrayConverted addObject:[NSString stringWithCString: cStr encoding:NSUTF8StringEncoding]];
}
Now you can replace the slow code with the much faster
NSString *msgDesc = [myContentsArrayConverted objectAtIndex:indexPath.row];
Related
I have bar code reader project in iOS...Now when my reader reads value starting with '0',it is giving me error.
eg. value '098876567' - Error
'I have tried to trim.It is working.But I face another problem.
If it found value '000877667676'
Again value starts with '0' so it is giving me error.
I am using sqlite3.
I know it is very basic question but still having problem.Help me.
My code is :
NSString *str = ID.text; //here ID field indicates read data from bar code reader
int test = [str intValue];
NSLog(#"get clicked");
[self databaseOpen];
NSString *getData = [NSString stringWithFormat:#"SELECT FName,LName FROM Emp WHERE Emp_ID = %d",test];
NSLog(#"getdata %#",getData);
NSArray *array = [adddatabase executeQuery:getData];
NSLog(#"array %#" , array);
getData = [[array objectAtIndex:0]valueForKey:#"FName"];
NSLog(#"update query:%#",getData);
fname.text = [NSString stringWithFormat:#"%#",getData];
NSString *lastname = [[NSString alloc]init];
lastname = [[array objectAtIndex:0] valueForKey:#"LName"] ;
NSLog(#"LName: %#",lastname);
lname.text=[NSString stringWithFormat:#"%#",lastname];
[adddatabase close];
[adddatabase release];
Can you share some code? Also, explain what sqlite3 (a database) has to do whit the barcode reader. Is the error from the barcode reader or from sqlite3?
I can imagine the error occuring when you read a barcode with leading zeroes, and try to store that in an integer field in your sqlite database. When storing a barcode you might want to use a String (TEXT) instead.
i want to localize my game. some of my label is like [#"Score: %i", score], and the score can be any number. so can i still use strings file localization?
this is what i do currently, but a lot of work
CCLabelTTF* bestLabelWord = [Helper createLocalizedLabelWithStringUpperCase:#"BEST" color:ccBLACK];
CCLabelTTF* bestLabelNumber = [Helper createUnlocalizedLabelWithString:[NSString stringWithFormat:#"%i", bestScore] color: ccBLACK];
bestLabelWord.anchorPoint = ccp(0, 0.5f);
bestLabelNumber.anchorPoint = ccp(0, 0.5f);
bestLabelWord.position = ccp(menuPosX, menuPosY2);
bestLabelNumber.position = ccp(menuPosX + bestLabelWord.contentSize.width + 5, menuPosY2);
[self addChild:bestLabelWord z:kZLabel];
[self addChild:bestLabelNumber z:kZLabel];
here i separate #"Score" and #"%i", score into 2 labels (word and number) and place them separately.
so how can i put them into one label? can i put like "NSString stringWithFormat" in localization.strings file?
Yes, you can do this. It looks like this (uncompiled; hopefully there is no typo):
NSString *scoreFormat = NSLocalizedString(#"Score: %d", #"Score format");
NSString *scoreString = [NSString stringWithFormat:scoreFormat, bestScore];
Your strings file for this in English would be:
/* Score format */
"Score: %d" = "Score: %d";
There is no difference between %d and %i. They are both specified by the standard. I personally prefer to express that it is "decimal" (vs. %x hexadecimal) rather than that it is an "integer" (vs. %f float). But it does not matter.
You should include the entire format statement in the strings file. You are localizing the entire format statement Score: %d. The rationale for this is to permit languages where the order might be different. For example, if there were a language where the correct translation were "%d score" or a language where to make sense you would have to say the equivalent of Score: %d points or Score: %d number.
If you don't want this kind of localization, and you will always put a colon after the label and a number after that, no matter the language, then you can localize just the label as you were in your original code, or like this:
NSString *localizedLabel = NSLocalizedString(#"Score", #"Score");
NSString *scoreString = [NSString stringWithFormat:#"%#: %d", localizedLabel, bestScore];
You should avoid calling NSLocalizedString with a variable parameter as you're suggesting. This is confusing, and can get in the way of using genstrings to create your strings file. That said, the following code is not a problem:
NSString * const kScoreLabelKey = #"Score";
NSString * const kPriceLabelKey = #"Price";
NSString *GetLocalizedStringForKeyValue(NSString *key, NSInteger value)
{
NSString *label = [[NSBundle mainBundle] localizedStringForKey:key value:nil table:#"Labels"];
NSString *valueLabel = [NSString stringWithFormat:#": %d", value];
return [label stringByAppendingString:valueLabel];
}
...
NSString *label = GetLocalizedStringForKeyValue(kScoreLabelKey, bestScore);
...
(In Labels.strings):
"Score" = "Score";
"Price" = "Price";
Things to note:
I created a separate strings file for this called Labels.strings. That way it doesn't impact using genstrings and the main Localizeable.string.
I used string constants for the keys. That puts all the strings used in one place at the top of the file, making it easy to audit against Labels.strings.
I have the follow code:
NSArray *myArray = [NSArray arrayWithObjects: #"e", #"è", #"é",#"i","ò",nil];
NSString *string = #"simpleè";
NSMutablestring *newString;
for(i=0>;i< [string length]; i++){
if([stringa characterAtIndex:i] is in Array){
[newString appendFormat:#"%c", [string characterAtIndex:i]];
}
}
How make finding if single char of string stay in the array?
Example of result:
newString= #"ieè";
I think you want to apply rangeOfCharacterFromSet:options:range: repeatedly. You'll have to create a NSCharacterSet from the characters in your array somehow.
Added
Though it probably would be just as simple to just loop through the string with characterAtIndex and compare each char (in an inner loop) to the chars in your array (which you could extract into a unichar array or put into a single NSString to make easier to access).
Umm... if you want to check what the values are you can use NSLog
NSLog"%f", myFloat;
So you can use this to check your array... Which is what I think you are asking for, but the grammar in your question isn't very good. Please provide more details and better grammar.
You should check the length of your string and then match your string characters with the array and if found append that character in a new string.
NSString *mstr = #"asdf";
NSString *b = [ mstr characterAtIndex:0];
Hope it helps.......
You'll want to create an NSCharacterSet with the characters in the string and then ask each string in the array for its rangeOfCharacterFromSet:. If you find one where a range was actually found, then a character from the string is in the array. If not, then none of them are.
This might seem a bit roundabout, but Unicode makes looking at strings as just a series of "chars" rather unreliable, and you'll want to let your libraries do as much of the heavy lifting for you as they can.
There are better ways to do this, but this is what I think you're trying to do:
NSMutableString* result= [NSMutableString stringWithString:#""];
for( int i= 0; i < [string length]; ++i ) {
NSString* c= [NSString stringWithFormat:#"%C", [string characterAtIndex:i]];
if( [myArray containsObject:c] )
[result appendString:c];
}
I have a paragraph (4 sentences) of text in an .plist array that loads into a UITextView.
By default, it presents the text how it is, as one big lump of text in a paragraph. I want to know if it is possible to split this up?
Such as Line 1: sdfafasfsafsa, then line 2: asfdsafs, line 3: adfsfsdfsdfa, etc.
Is there a way I can search for a . and then separate the lines accordingly? I would just edit the plist manually but there are hundreds of entries so it isn't easy to do.
NSString* tidiedString = [sourceString stringByReplacingOccurrencesOfString:#"." withString:#"\n"];
Update: OK, so more detail is coming through. You could use a regular expression - but if you're not familiar, the learning curve is a bit steep. Otherwise, as with other answers, crank through the list. You need to take care of whitespaces, empty lines etc. The following snippet isn't pretty, but will do the job.
NSString* sourceString = #"Hyperlinks can be great. They can also dilute your focus and tempt you into putting off what you most want to do. Here I chose to place links at the foot of the page to help you to make an active choice as to whether to surf or refocus your attention elsewhere.";
NSArray* arrayOfStrings = [sourceString componentsSeparatedByString:#"."];
NSMutableString* superString = [NSMutableString stringWithString:#""];
int lineCount = 1;
for (NSString* string in arrayOfStrings)
{
if ([string length] < 1) continue;
[superString appendFormat:#"Line %d: %#.\n", lineCount++, [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
[superString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[[self userEntry] setText:superString];
NSArray *array = [sourceString componentsSeparatedByString:#"."];
NSMutableString *resultString= [[NSMutableString alloc] init];
int linecount=1;
for(NSString *lines in array)
{
[resultString appendString:[NSString stringWithFormat:#"Line%i:%#\n",linecount++,lines]];
}
NSLog(#"resultString:%#",resultString);
this may help..!!
Try making a loop that runs through the array and that adds every line to the UITextView plus #"\n".
So something like...:
NSString *curText = txtView.text;
NSString *lineBreak = #"\n";
txtView.text=[NSString stringWithFormat:#"%# + %#", curText, lineBreak];
Or just replace the dots by #"\n".
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I concatenate strings in Objective-C?
Firstly, the platform is iPhone and label.text changes the label displayed. Consider this scenario:
I've an array of integers. And I want to display it on the screen.
Here's my take on it:
-(IBAction) updateText: (id)sender {
int a[2];
a[0]=1;
a[1]=2;
a[2]=3;
for (int i=0; i<=10;i++)
label.text = [NSString stringByAppendingString: [NSString stringWithFormat: #"%i", a[i]]];
}
As you can probably see, I'm pretty confused. Pls pls help me out :(
Try this:
NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
[theString appendString:[NSString stringWithFormat:#"%i ",i]];
}
label.text = theString;
Since you're using a loop, do be somewhat careful with both Tom and Benjie's solutions. They each create an extra autoreleased object per iteration. For a small loop, that's fine, but if the size of the loop is unbounded or if the strings are large, this can lead to a very large memory spike and performance hit. Particularly on iPhone, this is exactly the kind of loop that can lead to surprising memory problems due to short-lived memory spikes.
The following solution has a smaller memory footprint (it's also slightly faster and takes less typing). Note the call to -appendFormat: rather than -appendString. This avoids creating a second string that will be thrown away. Remember that the final string has an extra space at the end that you may want to get rid of. You can fix that by either treating the first or last iteration differently, or by trimming the last space after the loop.
NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
[theString appendFormat:#"%i ",i];
}
label.text = theString;
Don't forget [NSArray componentsJoinedByString:]. In this case you don't have an NSArray, but in the common cases where you do, this is probably the best way to get what you're looking for.
//NSArray *chunks
string = [chunks componentsJoinedByString: #","];
Another method without using NSMutableString:
NSString* theString = #"";
for (int i=0; i<=10;i++){
theString = [theString stringByAppendingFormat:#"%i ",i];
}
label.text = theString;
Here's a full implementation (correcting your ranges):
-(IBAction) updateText: (id)sender {
int a[3];
a[0]=1;
a[1]=2;
a[2]=3;
NSString *str = #"";
for (int i=0; i<3;i++)
str = [str stringByAppendingFormat:#"%i ",i];
label.text = str;
}
You could also do it like this (e.g. if you wanted a comma separated list):
-(IBAction) updateText: (id)sender {
int a[3];
a[0]=1;
a[1]=2;
a[2]=3;
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
for (int i=0; i<3;i++)
[arr addObject:[NSString stringWithFormat:#"%i",i]];
label.text = [arr componentsJoinedByString:#", "];
}