Unable to compare strings - objective-c

I am trying to compare two strings contry and answer.
myTextField is a textfield control and -country is NSArray
but it will always execute else block even when the two strings are equal
NSString *answer = _myTextField.text;
NSString *contry = _country[self.displayedFlagIndex];
if ( [contry isEqualToString: answer])
{
NSString *test =#"if block ";
NSString *result = [NSString stringWithFormat:#"%#%# is %#", test,answer, #"Correct!!"];
_myTextField.text= result;
}

Well, isEqualToString: works flawlessly. The only thing you need to mind is it does not do case insensitive comparison of string.
If you need that behaviour, please add following category on NSString and call it:
- (BOOL)isEqualIgnoreCaseToString:(NSString *)iString {
return ([self caseInsensitiveCompare:iString] == NSOrderedSame);
}

Related

How can i compare a NSString with two other NSStrings

My problem is that i have a NSString and i have to compare it with two other NSStrings.
How can i compare NSStrings like:
if(a == (b || c))
My resolution for this isn't fine yet (but works) :
NSString *a = #"myfirststring";
NSString *b = #"mysecondstring";
if([[NSString stringWithFormat:#"%s", MethodThatReturnsChar*] isEqual:a] || [[NSString stringWithFormat:#"%s",MethodThatReturnsChar*] isEqual:b])
{
}
The problem is that i have to call MethodThatReturnsChar* two times, that isn't necessary, is it?
that isn't necessary, is it?
Exactly, it's completely superfluous. That's why the C language has variables... Also, don't abuse - [NSString stringWithFormat:]. Furthermore, use isEqualToString: for comparison:
NSString *a = [NSString stringWithUTF8String:someCharPtr];
if ([a isEqualToString:b] || [a isEqualToString:c]) {
DoStuff();
}
Assign that string to a variable, and then compare it with the other strings
NSString *a = #"myfirststring";
NSString *b = #"mysecondstring";
NSString *stringIAmComparing = [NSString stringWithFormat:#"%s", MethodThatReturnsChar*];
if([stringIAmComparing isEqualToString:a] || [stringIAmComparing isEqualToString:b])
{
}
You can wrap your "MethodThatReturnsChar*" into another NSString using
NSString* stringToCompare = [NSString stringWithCString:yourCString encoding:NSUTF8StringEncoding];
and then compare:
if([stringToCompare isEqualToString:a] || [stringToCompare isEqualToString:b])
Hope that helps.

help with NSdictionary

I have an NSMutableArray where each item is an NSMutableDictionary.
NSMutableAray *services = [NSMutableArray new];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: aNetService forKey: #"net_service"];
[dict setObject: [aNetService name] forKey: #"net_service_name"];
[self.services addObject:dict];
Then I want to retrieve an item according to the "net_service_name" key. So, I tried the following:
-(void)netServiceBrowser:(NSNetServiceBrowser *)aBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)more {
NSLog(#"netservname%#",[aNetService name]);
for (int i = 0; i < [services count]; i++)
{
NSDictionary *dict = [services objectAtIndex:i];
NSLog(#"netservname%#",[dict objectForKey:#"net_service_name"]);
if ([NSString stringWithFormat:#"%#",[dict objectForKey:#"net_service_name"]] == [NSString stringWithFormat:#"%#",[aNetService name]]){
NSLog(#"Match");
}
}
}
In the console both NSLog(#"netservname") are the same, but I'm not getting the "Match" message. Can anyone see why? Thanks very much!
Try using
if ([[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]).
== checks for identity, that is whether the two objects point to the same memory address.
isEqualToString checks for equality, in this case, that the two strings are the same characters in the same order.
[[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]
Try that.
try this:
[[NSString stringWithFormat:#"%#",[dict objectForKey:#"net_service_name"]] isEqualToString:[NSString stringWithFormat:#"%#",[aNetService name]]]
or
[[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]
NSString isEqualToString:(NSString*) http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
see: Case-insensitive NSString comparison
Because Objective-C uses pointers for everything you can't directly compare strings with the == operator. What you're looking for is:
[string isEqualToString: otherString]
Always use isEqualToString: for NSString comparison.
(And in general, always use isEqual: and its variants for NSObject comparisons)
NSObject* and NSString* are pointers, so == do pointer comparison which is only true if the pointers are pointing to the exact same address in memory, which is quite never the case, while isEqualToString: check if the contents of the string are identical.
Besides, you should prefer fast enumerations form for your for loop, and avoid doing stuff like stringWithFormat:#"%#" which are totally useless (you are creating a string using a format that will only contain... another string. Why don't you use the string itself directly?)
// NSFastEnumeration for to loop thru a NSArray
for (NSDictionary *dict in services)
{
NSLog(#"netservname%#",[dict objectForKey:#"net_service_name"]);
// Loose the [NSString stringWithFormat:#"%#",...] stuff!!
if ([[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]) {
NSLog(#"Match");
}
}
Try to replace if-statement with this one:
if ([[dict objectForKey:#"net_service_name"] compare:[aNetService name]] == NSOrderedSame) {
NSLog(#"Match");
}

Compare two NSStrings

In my app there is a mechanism that requires that at a certain point two NSStrings will be the same to do something; for some reason when I compare the two, even when they are the same, it still doesn't recognize that. The code is something like this:
NSString * aString = [self someMethodThatGetsAString];
NSString * bString;
BOOL areStringsTheSame = NO;
while (areStringsTheSame != YES) {
bString = [self someMethodThatTakesNSStringsFromAnArrey];
if (bString == aString) {
areStringsTheSame = YES;
{ }
I even inserted an NSLog() and made sure that at a certain point they were the same (and as far as I know this is what == stands for...), but still it didn't get into the if to change the BOOL value.
Is there another way to do this comparison? Am I missing something?
You can use the method isEqualToString::
if ([bString isEqualToString:aString])
== compares the references (addresses of) the strings, and not the value of the strings.
This approach worked for me:
if ([firstString compare:secondString] == NSOrderedSame) {
//Do something when they are the same
} else {
//Do something when they are different
}
Recently I was shocked by the fact that two NSStrings that resemble each other on NSLog may be different. It is because sometimes NSString can contain a zero width space character. Be aware of that and consider:
#define ZERO_WIDTH_SPACE_STRING #"\u200B"
To conquer this you should clean your string from zero width white space characters before comparing:
NSMutableString *eMailToAdd = [NSMutableString string];
NSMutableCharacterSet *charSet = [[NSCharacterSet whitespaceCharacterSet] mutableCopy];
//[charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
NSString *rawStr = [[tokenField textField] text];
for (int i = 0; i < [rawStr length]; i++)
{
if (![charSet characterIsMember:[rawStr characterAtIndex:i]])
{
[eMailToAdd appendFormat:#"%#",[NSString stringWithFormat:#"%c", [rawStr characterAtIndex:i]]];
}
}

String comparison in Objective-C

I've currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a NSString containing a GUID and when I attempt to compare this with another NSString I get some strange results.
Why would this not fire? Surely the two strings are a match?
NSString *myString = #"hello world";
if (myString == #"hello world")
return;
Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.
if ([category isEqualToString:#"Some String"])
{
// Do stuff...
}
You can use case-sensitive or case-insensitive comparison, depending what you need.
Case-sensitive is like this:
if ([category isEqualToString:#"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:#"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
You can compare string with below functions.
NSString *first = #"abc";
NSString *second = #"abc";
NSString *third = [[NSString alloc] initWithString:#"abc"];
NSLog(#"%d", (second == third))
NSLog(#"%d", (first == second));
NSLog(#"%d", [first isEqualToString:second]);
NSLog(#"%d", [first isEqualToString:third]);
Output will be :-
0
1
1
1

How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?

Is there any way to create a new
NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
In the NSSTring class there are many methods like:
- (id)initWithFormat:(NSString *)format arguments:(va_list)argList
- (id)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList
+ (id)stringWithFormat:(NSString *)format, ...
but non of them takes a NSArray as an argument, and I cannot find a way to create a va_list from a NSArray...
It is actually not hard to create a va_list from an NSArray. See Matt Gallagher's excellent article on the subject.
Here is an NSString category to do what you want:
#interface NSString (NSArrayFormatExtension)
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
#end
#implementation NSString (NSArrayFormatExtension)
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments
{
char *argList = (char *)malloc(sizeof(NSString *) * arguments.count);
[arguments getObjects:(id *)argList];
NSString* result = [[[NSString alloc] initWithFormat:format arguments:argList] autorelease];
free(argList);
return result;
}
#end
Then:
NSString* s = [NSString stringWithFormat:#"xxx=%#, yyy=%#" array:#[#"XXX", #"YYY"]];
NSLog( #"%#", s );
Unfortunately, for 64-bit, the va_list format has changed, so the above code no longer works. And probably should not be used anyway given it depends on the format that is clearly subject to change. Given there is no really robust way to create a va_list, a better solution is to simply limit the number of arguments to a reasonable maximum (say 10) and then call stringWithFormat with the first 10 arguments, something like this:
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments
{
if ( arguments.count > 10 ) {
#throw [NSException exceptionWithName:NSRangeException reason:#"Maximum of 10 arguments allowed" userInfo:#{#"collection": arguments}];
}
NSArray* a = [arguments arrayByAddingObjectsFromArray:#[#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X"]];
return [NSString stringWithFormat:format, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9] ];
}
Based on this answer using Automatic Reference Counting (ARC): https://stackoverflow.com/a/8217755/881197
Add a category to NSString with the following method:
+ (id)stringWithFormat:(NSString *)format array:(NSArray *)arguments
{
NSRange range = NSMakeRange(0, [arguments count]);
NSMutableData *data = [NSMutableData dataWithLength:sizeof(id) * [arguments count]];
[arguments getObjects:(__unsafe_unretained id *)data.mutableBytes range:range];
NSString *result = [[NSString alloc] initWithFormat:format arguments:data.mutableBytes];
return result;
}
One solution that came to my mind is that I could create a method that works with a fixed large number of arguments like:
+ (NSString *) stringWithFormat: (NSString *) format arguments: (NSArray *) arguments {
return [NSString stringWithFormat: format ,
(arguments.count>0) ? [arguments objectAtIndex: 0]: nil,
(arguments.count>1) ? [arguments objectAtIndex: 1]: nil,
(arguments.count>2) ? [arguments objectAtIndex: 2]: nil,
...
(arguments.count>20) ? [arguments objectAtIndex: 20]: nil];
}
I could also add a check to see if the format string has more than 21 '%' characters and throw an exception in that case.
#Chuck is correct about the fact that you can't convert an NSArray into varargs. However, I don't recommend searching for the pattern %# in the string and replacing it each time. (Replacing characters in the middle of a string is generally quite inefficient, and not a good idea if you can accomplish the same thing in a different way.) Here is a more efficient way to create a string with the format you're describing:
NSArray *array = ...
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
[newArray addObject:[NSString stringWithFormat:#"x=%#", [object description]]];
}
NSString *composedString = [[newArray componentsJoinedByString:#", "] retain];
[pool drain];
I included the autorelease pool for good housekeeping, since an autoreleased string will be created for each array entry, and the mutable array is autoreleased as well. You could easily make this into a method/function and return composedString without retaining it, and handle the autorelease elsewhere in the code if desired.
This answer is buggy. As noted, there is no solution to this problem that is guaranteed to work when new platforms are introduced other than using the "10 element array" method.
The answer by solidsun was working well, until I went to compile with 64-bit architecture. This caused an error:
EXC_BAD_ADDRESS type EXC_I386_GPFLT
The solution was to use a slightly different approach for passing the argument list to the method:
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
{
__unsafe_unretained id * argList = (__unsafe_unretained id *) calloc(1UL, sizeof(id) * arguments.count);
for (NSInteger i = 0; i < arguments.count; i++) {
argList[i] = arguments[i];
}
NSString* result = [[NSString alloc] initWithFormat:format, *argList] ;// arguments:(void *) argList];
free (argList);
return result;
}
This only works for arrays with a single element
There is no general way to pass an array to a function or method that uses varargs. In this particular case, however, you could fake it by using something like:
for (NSString *currentReplacement in array)
[string stringByReplacingCharactersInRange:[string rangeOfString:#"%#"]
withString:currentReplacement];
EDIT: The accepted answer claims there is a way to do this, but regardless of how fragile this answer might seem, that approach is far more fragile. It relies on implementation-defined behavior (specifically, the structure of a va_list) that is not guaranteed to remain the same. I maintain that my answer is correct and my proposed solution is less fragile since it only relies on defined features of the language and frameworks.
For those who need a Swift solution, here is an extension to do this in Swift
extension String {
static func stringWithFormat(format: String, argumentsArray: Array<AnyObject>) -> String {
let arguments = argumentsArray.map { $0 as! CVarArgType }
let result = String(format:format, arguments:arguments)
return result
}
}
Yes, it is possible. In GCC targeting Mac OS X, at least, va_list is simply a C array, so you'll make one of ids, then tell the NSArray to fill it:
NSArray *argsArray = [[NSProcessInfo processInfo] arguments];
va_list args = malloc(sizeof(id) * [argsArray count]);
NSAssert1(args != nil, #"Couldn't allocate array for %u arguments", [argsArray count]);
[argsArray getObjects:(id *)args];
//Example: NSLogv is the version of NSLog that takes a va_list instead of separate arguments.
NSString *formatSpecifier = #"\n%#";
NSString *format = [#"Arguments:" stringByAppendingString:[formatSpecifier stringByPaddingToLength:[argsArray count] * 3U withString:formatSpecifier startingAtIndex:0U]];
NSLogv(format, args);
free(args);
You shouldn't rely on this nature in code that should be portable. iPhone developers, this is one thing you should definitely test on the device.
- (NSString *)stringWithFormat:(NSString *)format andArguments:(NSArray *)arguments {
NSMutableString *result = [NSMutableString new];
NSArray *components = format ? [format componentsSeparatedByString:#"%#"] : #[#""];
NSUInteger argumentsCount = [arguments count];
NSUInteger componentsCount = [components count] - 1;
NSUInteger iterationCount = argumentsCount < componentsCount ? argumentsCount : componentsCount;
for (NSUInteger i = 0; i < iterationCount; i++) {
[result appendFormat:#"%#%#", components[i], arguments[i]];
}
[result appendString:[components lastObject]];
return iterationCount == 0 ? [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] : result;
}
Tested with format and arguments:
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX", #"YYY", #"ZZZ"];
Result: xxx=XXX, yyy=YYY last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX", #"YYY"];
Result: xxx=XXX, yyy=YYY last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX"];
Result: xxx=XXX last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[];
Result: last component
NSString *format = #"some text";
NSArray *arguments = #[#"XXX", #"YYY", #"ZZZ"];
Result: some text
I found some code on the web that claims that this is possible however I haven't managed to do it myself, however if you don't know the number of arguments in advance you also need to build the format string dynamically so I just don't see the point.
You better off just building the string by iterating the array.
You might find the stringByAppendingString: or stringByAppendingFormat: instance method handy .
One can create a category for NSString and make a function which receives a format, an array and returns the string with replaced objects.
#interface NSString (NSArrayFormat)
+ (NSString *)stringWithFormat:(NSString *)format arrayArguments:(NSArray *)arrayArguments;
#end
#implementation NSString (NSArrayFormat)
+ (NSString *)stringWithFormat:(NSString *)format arrayArguments:(NSArray *)arrayArguments {
static NSString *objectSpecifier = #"%#"; // static is redundant because compiler will optimize this string to have same address
NSMutableString *string = [[NSMutableString alloc] init]; // here we'll create the string
NSRange searchRange = NSMakeRange(0, [format length]);
NSRange rangeOfPlaceholder = NSMakeRange(NSNotFound, 0); // variables are declared here because they're needed for NSAsserts
NSUInteger index;
for (index = 0; index < [arrayArguments count]; ++index) {
rangeOfPlaceholder = [format rangeOfString:objectSpecifier options:0 range:searchRange]; // find next object specifier
if (rangeOfPlaceholder.location != NSNotFound) { // if we found one
NSRange substringRange = NSMakeRange(searchRange.location, rangeOfPlaceholder.location - searchRange.location);
NSString *formatSubstring = [format substringWithRange:substringRange];
[string appendString:formatSubstring]; // copy the format from previous specifier up to this one
NSObject *object = [arrayArguments objectAtIndex:index];
NSString *objectDescription = [object description]; // convert object into string
[string appendString:objectDescription];
searchRange.location = rangeOfPlaceholder.location + [objectSpecifier length]; // update the search range in order to minimize search
searchRange.length = [format length] - searchRange.location;
} else {
break;
}
}
if (rangeOfPlaceholder.location != NSNotFound) { // we need to check if format still specifiers
rangeOfPlaceholder = [format rangeOfString:#"%#" options:0 range:searchRange];
}
NSAssert(rangeOfPlaceholder.location == NSNotFound, #"arrayArguments doesn't have enough objects to fill specified format");
NSAssert(index == [arrayArguments count], #"Objects starting with index %lu from arrayArguments have been ignored because there aren't enough object specifiers!", index);
return string;
}
#end
Because NSArray is created at runtime we cannot provide compile-time warnings, but we can use NSAssert to tell us if number of specifiers is equal with number of objects within array.
Created a project on Github where this category can be found. Also added Chuck's version by using 'stringByReplacingCharactersInRange:' plus some tests.
Using one million objects into array, version with 'stringByReplacingCharactersInRange:' doesn't scale very well (waited about 2 minutes then closed the app). Using the version with NSMutableString, function made the string in about 4 seconds. The tests were made using simulator. Before usage, tests should be done on a real device (use a device with lowest specs).
Edit: On iPhone 5s the version with NSMutableString takes 10.471655s (one million objects); on iPhone 5 takes 21.304876s.
Here's the answer without explicitly creating an array:
NSString *formattedString = [NSString stringWithFormat:#"%# World, Nice %#", #"Hello", #"Day"];
First String is the target string to be formatted, the next string are the string to be inserted in the target.
No, you won't be able to. Variable argument calls are solved at compile time, and your NSArray has contents only at runtime.