Why use NSRange on strings when there appears to be a perfectly good substring method? - ios

I'm learning native iOS development for the first time, and I came across the struct NSRange. I come from a Java background so I don't really see the reasoning for using a range struct when you can just use substring methods that are part of the NSString class. What is the advantage of using range structs over using the non-range NSString substring methods.
Thanks!
edit:
Looks like I was considering the substring methods: substringFromIndex: and substringToIndex:.
Considering the inflexibility of these methods (ie. not being able to choose both a start AND end point) makes the range struct instances more necessary. Though I guess you could also nest those two methods to achieve the same result.
edit 2: Examples.
Non-range substring method examples:
NSString *str = #"This is a string.";
NSString *substr = [str substringToIndex:7];
NSString *substr2 = [str substringFromIndex:7];
Ranges substring method example:
NSString *substr3 = [str substringWithRange:NSMakeRange(5, 5)];

Because the range based methods offer a lot more flexibility, and they are also easily usable with all of the NSString search methods (which use ranges heavily). In general, if you're going to create a substring you need to know where to start or end and that information is likely to have come from a search, thus you have a range.

Related

NSAttributedString & decomposedStringWithCanonicalMapping ranges

I'm running into problems with international (in this case Korean) NSString values.
The same input string is used in two different parts of the program. The first part finds a substring that needs highlighting, stores the NSString and the range for the highlighting into a database.
The second part of the program retrieves the string and displays the highlighting.
The marking part is done using an NSString that has been normalized in Unicode Normalization Form C using the precomposedStringWithCanonicalMapping method on NSString. An NSRange and an NSString are then stored into the Core Data database.
The graphical highlighting is performed by retrieving the NSRange and NSString from the database, putting the NSString into the same Form C using the same method, using this to initialize an NSMutableAttributedString and using the NSRange to set its text attributes.
At this stage, the program crashes because the NSMutableAttributedString is 80 characters long, whereas the NSString was 81 characters long..
NSAttributedString does not have a precomposedStringWithCanonicalMapping method and I assume it changes the representation internally resulting in a different encoding and thus length.
What can I do?
is the a way of forcing NSAttributedString to keep an underlying encoding?
is there a way of converting an NSRange from one encoding to another?
or is there anything else I can do?
Ok,
I did eventually find out what had happened. In one particular place in the program I mistakenly used decomposed​String​With​Canonical​Mapping rather than precomposed​String​With​Canonical​Mapping and that's where the "wrong" mapping came from.

How to code for a password needing a number and capital letter in objective c

Looking for coding or ideas to help me get a good start on ways for a program to check, after tapping a button, the a UITextField for at least one capital letter, at least one number and a length >= 6. Looking towards if statements so the else code could send out an alert telling its missing something.
am pretty much new to coding and was directed by my teacher to ask on here, thank you
I would recommend checking each one individually and then only logging on (progressing) if they all come back ok
Checking the length
// Check if the text is a certain length
if (textField.text.length >= 6) {
}
Checking that is contains a number
if ([textField.text rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) {
}
Checking that it contains an uppercase character
NSString * string = textField.text;
int count = 0;
for (i = 0; i < [s length]; i++) {
BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:i]];
if (isUppercase == YES)
count++;
}
This code is from here and loops through the string checking if there are upper case characters contained in it. You can then check the value of count to see if there is at least one it in. If you want a stronger password you can increase this check too.
In future though this is all quite basic stuff which just requires time to find out instead of knowledge of C. I didn't know how to do any of this before having a look to write this answer.
Hopefully this helps your understanding and, going forward, try spending 30 minutes searching with google before posting a duplicate question
Some more good questions on this can be seen below.
This answer here: is almost the same as the one you have asked
This answer also covers special characters: here
As Hot Licks says, this is not a "write my code for me" site. This is a site to get help with specific problems.
Take a look at the NSString class reference in Xcode. You should read the whole thing. It lists lots and lots of very useful methods. You won't understand it all at first, but note methods that sound like the would be useful.
Big hint: You'll also want to take a look at the NSCharacterSet class, and NSString methods that use NSCharacterSet to search in a string for characters that belong to specific set of characters.
Note that you could probably also use regular expressions. Cocoa includes the NSRegularExpression class, which lets you apply regular expressions to strings.

Objective-C: Two 'identical' strings do not match?

I have a two strings.
Once is a response from a TCP server using NSStream events, using:
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
And one is a string produced from on the fly, that should match the returned string from the NSStream.
I have NSLog both of these out, and they are identical.
I have tried to NSLog the Lengths of the strings, and one is two characters longer - Even though they are both identical in 'text' form.
Any suggestions to point me in the right direction?
I need to know if they match, as if they do, another event will be triggered to enhance and add additional functionality to my app.
Never use == to compare strings. If their contents are character-by-character identical, you can use isEqualToString to compare 2 strings. If your strings have different lengths, though, then they are not character-by-character identical.
Write a for loop that uses the method characterAtIndex to log the characters from each string 1 at a time and compare them. You might need to log the characters' integer values so you can see info about the non-printable ones.
Thanks Guys.
Fixed with #rdelmar suggestions - I didn't know this was possible in Objective-C:
NSString *trimOutput = [output stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Compare Phone Numbers with different format

Phone nubmber can have different Formats , like 0XXXXXXXXXX or +91XXXXXXXXXX or XXXXXXXXXX.
In all cases , phone number is similar.
How can i compare ?
Please do this for love of god: Handling all formats of phone numbers is as tricky and hairy as handling different data formats. It's always a sane option to use some existing "mature" library. Use PhoneNumberKit, its one of the mature and popular libraries out there.
But if you want to live on the edge, you can try something like this -
Reverse the string & compare only the first 10 chars.
Regular Expressions would be a better solution. Have as many regular expressions as there are formats & you are good to go.
Please open source this library for others to benefit :)
General reading on handling phone numbers
You could start comparing right to left using a custom character by character match code. It also works because the last few digits on phones vary more than the first few, so your code will fail fast in a unequal comparison which is what you want anyways. Keep a count of how many matches you have and if it passes a certain threshold say 10, then call the number equal. Without know more specifics this would be made to work reasonably well.
As Mentioned by srikar to reverse the string and compare 10 characters.Create the method and call it for all the three strings and after that compare them.
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [myString length];
NSInteger count;
count=10;
while(count >= 0) {
count--;
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[myString substringWithRange:subStrRange]];
}

What is differnce between NSString and NSCharacterset?

I studying NSCharacterset class.
NSString and NSCharacterset look like similar class.
Who can explain difference between NSString and NSCharacterset?
When use NSCharacterset?
Thanks your help..
An NSString object represents a string of ordered characters (text). An NSCharacterSet object represents a set of characters in no particular order. It is often much quicker to determine whether a character is a member of an NSCharacterSet than an NSString. You can't use an NSCharacterSet object to hold text, at least not in any sensible way, because it does not maintain any order of characters, its use is primarily for determining whether a character exists in a set of characters.

Resources