I’m trying to loop through a NSString, character by character, but I’m getting a EXC_BAD_ACCESS error. Do you have an idea how to do this right? I’ve been googling for hours now but can’t figure it out.
Here is my code (.m):
self.textLength = [self.text length];
for (int position=0; position < self.textLength; position++) {
NSLog(@"%@", [self.text characterAtIndex:position]);
if ([[self.text characterAtIndex:position] isEqualToString:@"."]){
NSLog(@"it's a .");
}
}
Thanks a lot!
Characters are not object.
characterAtIndexreturnsunichar, which is actually an integer typeunsigned short. You need to use%Cinstead of%@inNSLog. Also character is not aNSString, so you can’t send itisEqualToString. You need to usech == '.'to comparechagainst'.'.Note that,
'a'is character,"a"is C string and@"a"is NSString. They all are different types.When you are using
%@with unicharchinNSLog, it is trying to print an object from memory locationchwhich is invalid. Thus you are getting a EXC_BAD_ACCESS.