NSMutableString performance - ios

I want to create a string. Based on condition I have to append some extra string. In this case which is preferred to use? Whether creating two different strings based on condition or creating mutable string to append a new string based on condition ?
EX
if(a==1)
{
String = "apple seed"
}
else
{
String = "apple"
}
Or
NSMutableString *string ;
string = #"apple";
if( a==1)
{
[string appendString:#"seed"]
}

A string literal, like your #"apple", is a compile-time constant so assigning a string literal to a variable of type NSString * is a cheap operation.
So for your particular examples the first selects one of two simple assignments, while the second can do a simple assignment and a method call - which is clearly going to take a little more time.
That said a "little more" on a modern computer is not long. Beware of optimising prematurely; it is far better to write code that is clear and understandable to you first and concern yourself over performance of minutiae later if needed (this is not an excuse to write poor algorithms or intentionally bad code of course).
HTH

Related

Which way is the most efficient to define a empty String in Swift?

I know 4 different types how to define an empty String in Swift.
var newString = ""
var newString: String = ""
var newString: String = String()
var newString = String()
Which way is the most efficient way when it comes to how fast the code gets executed?
Is there even a different between them?
There's only really two different techniques here:
Using an empty string literal: var newString = ""
Calling empty String initializer: var newString = String()
The other two are just these two techniques, but with an explicit type annotation. Type annotations are a compile-time only aspect of your program, which exist only to communicate types to the compiler, with no impact at run-time. In this case, both variables would have been inferred to be String*, so these type annotations are redundant, and don't tell the compiler anything you didn't already know.
These two approaches should have the exact same run-time characteristics.
The compiler can intern string constants to prevent repetitions of the same string literals from being repeated in the final application binary. This actually wouldn't be relevant here, because Swift uses tagged pointers to store "small strings" (IDR what exactly constitutes "small"), meaning don't even require heap allocation.
In a sense, that means that having a short string like "abc" in your code is no different than 123. It's just a small value that's pushed onto the stack when you enter your function.
If you're coming from other languages, you might expect String() to result in a different instance on every call, but that isn't actually the case in Swift. There is no instance allocated at all, just an empty string as represented by the small-string storage, which is stored inline. The compiler should also be able to recognize that String() always results in the same value, which it should be able to inline, much like how Int() gets replaced with 0.
* Actually, if you define a type named StringLiteral in your module, the inferred type of "" will be your StringLiteral type rather than the default String.

How to remove hexadecimal characters from NSString

I am facing one issue related some hexa value in string, i need to remove hexadecimal characters from NSString.
The problem is when i print object it prints as "BLANK line". And in debug mode it shows like :
So how can i remove it from the string?
EDIT
Triming whitespace :
result of NSLog is :
2015-12-14 15:37:10.710 MyApp [2731:82236] tmp :''
Database:
Earlier question:
how to detect garbage string value in ios?
As your dataset clearly has garbage values, You can use this method to check if your string is valid or not. Define your validation criteria and simply don't entertain the values which are garbage. But as suggested before by gnasher, you should rather look for the bug which is causing insertion of garbage data in your database. Once you have done that, check if the input string matches your defined criteria. If it does, do what you want. If it doesn't, simply move on.
-(BOOL) isValidString: (NSString*) input
{
NSMutableCharacterSet *validSpecialChars = [NSMutableCharacterSet characterSetWithCharactersInString:#"_~.,"];//Add your desired characters here
[validSpecialChars formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
return [[input stringByTrimmingCharactersInSet:validSpecialChars] isEqualToString:#""];
}
If your string will contain only your defined characters, it will return true. If it contains any other characters (garbage or invalid) it will return false.
I'm not sure exactly what you are looking for, but if you want to remove all the control characters then
string = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet controlCharacterSet]] componentsJoinedByString:#""]
If you need to be faster and are sure the control characters are only at the beginning and ending of a string then
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
NOTE: Removing all control characters will remove all new lines (\n)!
From NSCharacterSet Class Reference:
These characters are specifically the Unicode values U+0000 to U+001F and U+007F to U+009F.
The value you are having a problem with is \x06 which is U+0006.
If you want to remove just \x06, then you can always create a characters set just for it.
NSCharacterSet *hex6 = [NSCharacterSet characterSetWithCharactersInString:#"\x06"];
string = [[string componentsSeparatedByCharactersInSet:hex6] componentsJoinedByString:#""]
First, don't trust the Xcode debugger. Print characterAtIndex:0 to be sure that you really have what you think you have.
Second, deleting stuff is all good and well, but you are doctoring around with a symptom. You should really try to figure out where the contents of _lastUpdatedBy comes from and why it is what it is. You might have a serious bug here and trying to cover it up. For example, there might be a bug that stores rubbish data instead of the correct data, and you are just covering up for that bug.

How long has NSString concatenation been supported?

I've just come across this line in some legacy code I'm editing:
[UIImage imageNamed:#"data/visuals/interface/" #"backgroundViewController"];
^^^^
"Oops, what have I done here?"
I thought I must have accidentally just pasted something in the wrong place, but an undo didn't change that line. Out of curiosity, I built the program and it was successful!
Whaddyaknow? Obj-c has a more succinct way of concatenating string literals.
I added some more tests:
A simple log
NSLog(#"data/visuals/interface/" #"backgroundViewController");
data/visuals/interface/backgroundViewController
In parameters
NSURL *url = [NSURL URLWithString:#"http://" #"test.com" #"/path"];
NSLog(#"URL:%#", url);
URL:http://test.com/path
Using Variables
NSString *s = #"string1";
NSString *s2 = #"string2";
NSLog(#"%#", s s2);
Doesn't compile (not surprised by this one)
Other literals
NSNumber *number = #1 #2;
Doesn't compile
Some questions
Is this string concatenation documented anywhere?
How long has it been supported?
What is the underlying implementation? I expect it will be [s1 stringByAppendingString:s2]
Is it considered good practice by any authoritative body?
This method of concatenating static NSStrings is a compile-time compiler capability that has been available for over ten years. It is usually used to allow long constant strings to be split over several lines. Similar capabilities have been available in "C" for decades.
In the C Programming Language book, 1988 second edition, page 38 describes string concatenation so it has been around for a long time.
Excerpt from the book:
String constants can be concatenated at compile time:
"hello," " world" is equivalent to "hello, world"
This is useful for spitting long strings across several source lines.
Objective-C is a strict superset of "C" so it has always supported "C" string concatenation and my guess is that because of that static NSString concatenation has always been available.
It is considered good practice when used to split a static string across several lines for readability.

Rails: Given a String, check if an Array (of strings) contains a substring of String

Is there a more Railsy way to do this (without explicit regex, perhaps?):
array_o_strings = ["some strings", "I'd like", "to parse"]
string = "like to parse"
re = Regexp.union(array_o_strings.map { |i| Regexp.new(i) })
string =~ re
Just pining for magical Rails methods.
There's really nothing wrong with using a regular expression here if that's your intent. It's generally more efficient to use one of those than to go through the trouble of comparing arrays.
It's worth noting you don't have to do that much work to get this:
re = Regexp.union(array)
That should handle automatically escaping those strings and compiling them into a singular regular expression. Test with strings containing * and ? to be sure.
One note to add on style is that the =~ operator is a hold-over from Perl. It's preferable to use string.match(re) to make it clear what's going on there.
How big is the array? It may be worth comparing the speed using a regex vs checking each element. If the array is sorted shortest to longest that would help when checking one by one as you're more likely to find a match first.
In any event, this is one way:
array_o_strings.any?{|e| string.index(e) }

Understanding the Use of invertedSet method of NSCharacterSet

So as I work my way through understanding string methods, I came across this useful class
NSCharacterSet
which is defined in this post quite well as being similar to a string excpet it is used for holding the char in an unordered set
What is differnce between NSString and NSCharacterset?
So then I came across the useful method invertedSet, and it bacame a little less clear what was happening exactly. Also I a read page a fter page on it, they all sort of glossed over the basics of what was happening and jumped into advanced explainations. So if you wanted to know what this is and why we use It SIMPLY put, it was not so easy instead you get statements like this from the apple documentation: "A character set containing only characters that don’t exist in the receiver." - and how do I use this exactly???
So here is what i understand to be the use. PLEASE provide in simple terms if I have explained this incorrectly.
Example Use:
Create a list of Characters in a NSCharacterSetyou want to limit a string to contain.
NSString *validNumberChars = #"0123456789"; //Only these are valid.
//Now assign to a NSCharacter object to use for searching and comparing later
validCharSet = [NSCharacterSet characterSetWithCharactersInString:validNumberChars ];
//Now create an inverteds set OF the validCharSet.
NSCharacterSet *invertedValidCharSet = [validCharSet invertedSet];
//Now scrub your input string of bad character, those characters not in the validCharSet
NSString *scrubbedString = [inputString stringByTrimmingCharactersInSet:invertedValidCharSet];
//By passing in the inverted invertedValidCharSet as the characters to trim out, then you are left with only characters that are in the original set. captured here in scrubbedString.
So is this how to use this feature properly, or did I miss anything?
Thanks
Steve
A character set is a just that - a set of characters. When you invert a character set you get a new set that has every character except those from the original set.
In your example you start with a character set containing the 10 standard digits. When you invert the set you get a set that has every character except the 10 digits.
validCharSet = [NSCharacterSet characterSetWithCharactersInString:validNumberChars];
This creates a character set containing the 10 characters 0, 1, ..., 9.
invertedValidCharSet = [validCharSet invertedSet];
This creates the inverted character set, i.e. the set of all Unicode characters without
the 10 characters from above.
scrubbedString = [inputString stringByTrimmingCharactersInSet:invertedValidCharSet];
This removes from the start and end of inputString all characters that are in
the invertedValidCharSet. For example, if
inputString = #"abc123d€f567ghj😄"
then
scrubbedString = #"123d€f567"
Is does not, as you perhaps expect, remove all characters from the given set.
One way to achieve that is (copied from NSString - replacing characters from NSCharacterSet):
scrubbedString = [[inputString componentsSeparatedByCharactersInSet:invertedValidCharSet] componentsJoinedByString:#""]
This is probably not the most effective method, but as your question was about understanding
NSCharacterSet I hope that it helps.

Resources