How to split a string from UITextField - ios

I have a UITextField as following:
_itemTextField = [[UITextField alloc];
This UITextField may contain item number only ex: "11321" or item number and size ex: "11321-XS" or "12355-40".
I want to extract the item and size (if it's available) separately in two different variables, as following:
NSString *itemNumber = #"11321";
NSString *itemSize = #"XS";
Please advise.

NSString *str = #"11115-ex";
if([str containsString:#"-"]){
NSArray * arr =[str componentsSeparatedByString:#"-"];
NSString *first = [arr objectAtIndex:0];
NSString *second = [arr objectAtIndex:1];
NSLog(#"Return String %# %#",first,second);
}
else
{
NSLog(#"Return String %#",str);
}

Related

How to force cast and convert datatype in objective c

Im a swift developer with no knowledge in objective c.
Can any one help me with converting the below code in Objective C
let newVersion = Int((userInfo.value(forKey:
"gcm.notification.version") as string).replacingOccurrences(of: ".", with: ""))
let currentVersion = Int((userDefaults.standard.value(forKey: "currentAppVersion") as string).replacingOccurrences(of: ".", with: ""))
if(newVersion > currentVersion) {
//code here
}
NSString *newVersion = [(NSString *)[notification.userInfo valueForKey:#"gcm.notification.version"] stringByReplacingOccurrencesOfString:#"." withString:#""];
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSString *oldVersion = [(NSString *)[standardDefaults valueForKey:#"currentAppVersion"] stringByReplacingOccurrencesOfString:#"." withString:#""];
if ([newVersion integerValue] > [oldVersion integerValue]){
//code here
}
Something like the following should do:
NSDictionary *userInfo; // Assuming this is a dictionary
NSString *newVersionString = userInfo[#"gcm.notification.version"];
newVersionString = [newVersionString stringByReplacingOccurrencesOfString:#"." withString:#""];
NSInteger newVersion = [[[NSDecimalNumber alloc] initWithString:newVersionString] integerValue];
NSString *currentVersionString = [[NSUserDefaults standardUserDefaults] valueForKey:#"currentAppVersion"];
currentVersionString = [currentVersionString stringByReplacingOccurrencesOfString:#"." withString:#""];
NSInteger currentVersion = [[[NSDecimalNumber alloc] initWithString:currentVersionString] integerValue];
if(newVersion > currentVersion) {
//code here
}
But this is not how you compare versions. The problem now is that for instance 1.11.1 is equal to 11.1.1. Or in other words reposition dots anyway you can but if number of digits and their order stay the same then you will detect it as a same version. You should do this per component (both in Swift or Objective-C):
NSDictionary *userInfo;
NSArray<NSString *> *newComponents = [userInfo[#"gcm.notification.version"] componentsSeparatedByString:#"."];
NSString *currentVersionString = [[NSUserDefaults standardUserDefaults] valueForKey:#"currentAppVersion"];
NSArray<NSString *> *currentComponents = [currentVersionString componentsSeparatedByString:#"."];
BOOL newVersionIsGreater = NO;
if(newComponents.count != currentComponents.count) newVersionIsGreater = newComponents.count > currentComponents.count;
else {
for(int i=0; i<newComponents.count; i++) {
NSInteger newInteger = [[[NSDecimalNumber alloc] initWithString:newComponents[i]] integerValue];
NSInteger currentInteger = [[[NSDecimalNumber alloc] initWithString:currentComponents[i]] integerValue];
if(newInteger != currentInteger) {
newVersionIsGreater = newInteger > currentInteger;
break;
}
}
}
if(newVersionIsGreater) {
//code here
}
This now checks if we have same number of components in both cases and then iterates through them. The first component that differs will report a change.

create new UILabel when conditions are met looping through NSArray

I have an NSArray with various parts divided by ,.
this array is much longer
citiesArray10000 = [NSArray arrayWithObjects:
#"33.572162&-112.087966&Phoenix&Arizona",
#"32.154289&-110.871062&735&Tucson Arizona ",
#"33.401926&-111.717379&Mesa&Arizona",
#"33.282874&-111.854943&Chandler&Arizona",
nil];
I loop through these to see if they meet certain conditions.
[citiesArray10000 enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// do something with object
NSArray *coorArray = [object componentsSeparatedByString:#"&"];
NSString *firstString = [coorArray objectAtIndex:0];
NSString *secondString = [coorArray objectAtIndex:1];
NSString *thirdString = [coorArray objectAtIndex:2];
NSString *fourthString = [coorArray objectAtIndex:3];
if (fabs(crnLoc.coordinate.latitude - latitude) <= 1) {
if (abs(crnLoc.coordinate.longitude - longitude <= 1)) {
self.label.text = fourthString;
}
}
the labels will float on the surface of the screen depending on the coordinates of the object that meet the conditions
self.label.frame = CGRectMake(160,(((self.mheading-90)-β)*-5.688)+200, 30, 200);
self.label2.frame = CGRectMake(160,(((self.mheading-90)-β)*-5.688)+200, 30, 200);
where β has different values depending on the coordinates.
the problem is that if more than one object in the array meets the conditions I need to create another label and have it's text be the fourthString of that object. Then when the condition isn't met any more delete that label. Is there anyway to do this?
How about using tag?
When you iterating through the citiesArray10000 array, I think you can add a tag to the uilabel and later on, when the conditions not meet anymore, you can find the label by the tag and delete the label.
[citiesArray10000 enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// do something with object
NSArray *coorArray = [object componentsSeparatedByString:#"&"];
NSString *firstString = [coorArray objectAtIndex:0];
NSString *secondString = [coorArray objectAtIndex:1];
NSString *thirdString = [coorArray objectAtIndex:2];
NSString *fourthString = [coorArray objectAtIndex:3];
if (fabs(crnLoc.coordinate.latitude - latitude) <= 1) {
if (abs(crnLoc.coordinate.longitude - longitude <= 1)) {
UILabel *label = (UILabel *)[self.view viewWithTag:idx];
label.text = fourthString;
// add the label to the view ...
}
}
}

add string dynamically in objc

I want to add string value dynamically from result.text and I wanted to display it in this way [#"17052648287",#"17052607335"] without losing the value. How can I do it?
NSMutableArray *strings = [#[#"17052648287",#"17052607335"] mutableCopy];
Add on coding
- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result{
if (!result) return;
if(self.hasScannedResult == NO)
{
//Scan Result, added into array
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text];
scanLists = [NSMutableArray new];
[scanLists addObject:scanPackage];
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *strings = [[NSMutableArray alloc]init];
strings = [#[result.text] mutableCopy];
[preferences setObject:strings forKey:#"strings"];
NSMutableArray *stringsArray = [preferences objectForKey:#"strings"];
for (NSString *string in stringsArray) {
NSLog(#"string: %#", string);
}
Declare an results array:
NSMutableArray * array = [NSMutableArray new];
Write below code where you get your result.text:
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text]; // If this code is working for you
[array addObject: scanPackage];
NSString *combined = [array componentsJoinedByString:#","];
NSLog(#"combined: %#", combined);

Loading text from .txt file iOS

I've been trying to convert a Quiz app that was based for Mac OS to iOS because I liked the idea of loading all questions from a single .txt file.
I'm still pretty new in the Objective-C language as I've used C# before.
The questions and answers are loaded via this function:
- (void)loadQuestionsAndAnswersArray {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA) {
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++) {
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound) {
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
}
The app then has a text field for the question and then 3 buttons, one for each answer. And when a new questions appears it changes the text within the text field and the title of the buttons.
This code works like a charm on the Mac App but on the iOS version it's like it can't find the txt file, the buttons etc is left blank.
I've been sitting on this for a week or so about now and that's the reason for this post.
The iOS app is based on this Github Mac app: https://github.com/SquaredTiki/Quizzer
If you want to have a look at how I've tried to convert the app here's a link to that to:
https://www.dropbox.com/s/1jqz9ue97p3v2h1/iTrafikk.zip?dl=0
And of course I'm not asking you to solve the whole issue for me, maybe just push me in the right direction if possible :)
I checked your project. And it seems that you are not calling loadQuestionsAndAnswersArray anywhere in your code. Also you are not initializing the questionsAndAnswers anywhere in the project.
Change your code like:
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadQuestionsAndAnswersArray];
}
- (void)loadQuestionsAndAnswersArray
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA)
{
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++)
{
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound)
{
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
if (!questionsAndAnswers)
{
questionsAndAnswers = [[NSMutableArray alloc] init];
}
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
[self loadQuestionsAndAnswersIntoInterface];
}

NSString subsstring

I have a string like this
12,23,45,3,12,
What I want to do is get this each number and check with an array value. How I can get each value as a substring to check
Thanks
Break this string to array.
NSString *string = #"12,23,45,3,12,";
NSArray *array = [string componentsSeparatedByString:#","];
Then you can compare with the array.
EDIT :
As per your comment that you want to check all the string values to be present in main-other-array.
NSString *string = #"12,23,45,3,12";
NSArray *array = [string componentsSeparatedByString:#","];
//below is the main-other-array
NSArray *toCheckArray = #[#"124",#"23",#"45",#"3",#"12",#"1000"];
BOOL arrayIsContainedInToCheckArray = YES;
for (NSString *arrayObj in array) {
if (![toCheckArray containsObject:arrayObj]) {
arrayIsContainedInToCheckArray = NO;
}
}
NSLog(#"%#",arrayIsContainedInToCheckArray?#"All exist":#"All doesn't exist");
May be it helps you :
NSString *str = #"12,23,45,3,12";
NSArray *strArray = [str componentsSeparatedByString:#","];
NSArray * anotherArray = nil; // have some value
for (NSString * value in strArray)
{
int intVal = [value integerValue]; // here is your separate value
for (int i = 0; i < [anotherArray count]; i++) // You can check against another array
{
id anotherVal = [anotherArray objectAtIndex:i];
// Here you can check intVal and anotherVal from another array
}
}
Use this, It will help you..
NSArray *detailArray = [yourString componentsSeparatedByString:#","];

Resources