NSString question - rangeOfString method - iphone

I am having an issue that I can't figure out.
I'm trying to run the rangeOfString method on a string, and I'm not sure how to determine if the string was not found. For example:
NSRange range = [#"abc" rangeOfString:#"d" options:NSCaseInsensitiveSearch range:NSMakeRange(0,3)];
Clearly, "d" is not contained in the string "abc." I'd like to be able to do this:
if(the range is empty since "d" is not in "abc")
//do something
What is the code for this?
Thanks!!

From the documentation of NSString
-[NSString rangeOfString]
Return Value
An NSRange structure giving the
location and length in the receiver of
the first occurrence of aString.
Returns {NSNotFound, 0} if aString is
not found or is empty (#"").
So it looks like:
if ([#"abc" rangeOfString:#"d"].location == NSNotFound){
//Do something
Is the Apple-approved way.
EDIT:
I made a really bad typo, fixed it, thanks Kalle.

Check the length of the range. If it's non-zero, it was found.

Related

NSLog pointer syntax

I'm a little bit confused about the syntax of NSLog. For example,
NSString *nameString = #"Name";
NSLog(#"nameString is: %#", nameString);
If my understanding is correct (which it very well may not be), then nameString is defined to be a pointer to a String. I thought then that this would print the memory address that nameString holds, not the value of that address. So, if that is true, then in the NSLog statement, to get the value of the pointer, shouldn't we need to use the asterisk notation to access what nameString points to like this:
NSLog(#"nameString is: %#", *nameString);
?
It has been a little while since programming in C, but since Objective-C is a superset of C I thought they would behave similarly.
An explanation would be greatly appreciated! Thanks!
The command %# is like "shortcut" that calls the method -description on the receiver. For an NSString it simply display the string itself, since is inherited from NSObject you can override it, very usefull if you create for own class. In that case the default behaviur is print the value of the pointer. If you want to print the address of the pointer in the string just replace with :
NSLog(#"nameString is: %p", nameString)
I think that you use an asterisk only to declare a pointer. Then, you only use the name you decided. For example:
NSString *foo = [[NSString alloc] initWithString:#"Hello"];
NSLog(#"%#", foo);
Correct me if I am wrong :)
It's an object and NSLog is a function that uses its format specifiers to determine what to do with the argument. In this case the specifier is %# which tells NSLog to call a method on an object.
Normally this will call the method "description" which returns an NSString but it probably does respondsToMethod first and falls through to some other string methods.

CFURLCreateStringByAddingPercentEscapes returning NULL

I am having issues with a category method used to percent-escape illegal symbols.
This is the code that i am using for the task:
#implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
NSString *s = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",CFStringConvertNSStringEncodingToEncoding(encoding));
NSLog(#"S: %#, Self: %#", s, self);
return [s autorelease];
}
#end
When ever i run this method on a string without any of the symbols found in the above matching-string, the method runs fine and the same string is returned back to me.
For instance if i have a string like #"test" it will output:
S: test, Self: test
But if i instead use a string like #"test&symbols" it will output:
S: null, Self: test&symbols
Hence something seems to be wrong with the use of CFURLCreateStringByAddingPercentEscapes.
Now i want to escape symbols such as & because they can occur in strings used as values in a query string, which would cause the query string to be misinterpreted.
Any idea's about what may be the issue here?
Thank you in advance! / Magnus
After finding out my big mistake.
I was told to answer the question to my self.
What i did wrong that i didn't pass NSStringEncoding value to the method, like NSUTF8StringEncoding but instead of that I was passing a CF value such as kCFStringEncodingUTF8.
The value is passed thru a converter to make it CF value which caused an error and it was already had the correct type.
Sorry for any inconvenience.
-Magnus

Objective C: Compare Array Element to String

Greetings,
I'm trying to simply compare a NSString to an NSArray.
Here is my code:
NSString *username=uname.text;
NSString *regex=#"^[a-zA-Z0-9-_.]{3,20}$";
NSArray *matchArray=nil;
matchArray=[username componentsMatchedByRegex:regex];
if(matchArray[0] == "asdf"){ //this line causes the problem!
NSLog(#"matchArray %#",matchArray);
}
I get an "invalid operands to binary ==" error.
How can I compare the string?
Many thanks in advance,
You are trying to compare an NSString to a C string (char *), which is wrong. matchArray is an NSArray so you cannot treat it as a C array either, you have to use its objectAtIndex: method and pass in the index.
Use this instead:
if ([[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
Addressing your comments, the reason why isEqualToString: does not show up in autocomplete is because Xcode cannot guess that matchArray contains NSStrings (it only knows it contains ids, that is, arbitrary Objective-C objects). If you really wanted to be sure, you can perform an explicit cast, but it doesn't matter if you don't:
if ([(NSString *)[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
you want to use -objectAtIndex to get the array element. NOT the C array accessor syntax
try to use:
[[matchArray objectAtIndex:0] isEqualToString:#"asdf"];
anyway the string "asdf" should be #"asdf"

How can I remove quotes from an NSString?

I am trying to remove quotes from something like:
"Hello"
so that the string is just:
Hello
Check out Apple's docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
You probably want:
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
So, something like this should work:
newString = [myString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
I only wanted to remove the first quote and the last quote, not the quotes within the string so here's what I did:
challengeKey = #"\"I want to \"remove\" the quotes.\"";
challengeKey = [challengeKey substringFromIndex:1];
challengeKey = [challengeKey substringToIndex:[challengeKey length] - 1];
Hope this helps others looking for the same thing. NSLog and you'll get this output:
I want to "remove" the quotes.

If UITextField or NSString is empty

If I want to check whether a UITextField or NSString is empty, can I compare it with NULL or nil?
Neither of the methods you suggest are foolproof. The best tests are:
if ([myTextField.text length] > 0) ...
or
if ([myString length] > 0) ...
if i want to check whether a textfield or string is empty i compare it with NULL or nil?
No.
An empty string object (a string object containing no characters) or a text-field object containing an empty string object is not the same as nil, which is no object at all. You need to ask the (text field's) string how long it is, or ask it whether it is equal to an empty string you have on hand (#"").
NULL, while also a null pointer, should be used for general pointers, not pointers to Objective-C instances (for which you have the more specific nil) or classes (for which you have the more specific Nil).
I had a similar problem but no method other than this worked for me:
NSString *string = textfield.text;
if ([string isEqualToString:#""]) {
....
}