Lazar K Lazar K - 3 months ago 15
Objective-C Question

IOS Array break up error

I call my server and receive a response with a long string that I break apart and store into arrays. I did this perfectly on Android but can't seem to figure it out in xcode. This is what I have to do for IOS:

Android:

while (flag) {
ProductListArray.add(ProductListOneString.substring(0, ProductListOneString.indexOf('_')));
ProductListOneString = ProductListOneString.substring(ProductListOneString.indexOf('_'));

if (ProductListOneString.equals("_")) {
flag = false;
} else {
ProductListOneString = ProductListOneString.substring(1);
}
}


int index = 2;
int ArraySize = ProductListArray.size();
ProductKeycodes = new ArrayList<>();
while(ArraySize > 0){
ProductKeycodes.add(ProductListArray.get(index));
index = index + 3;
ArraySize = ArraySize - 3;
}


what i have so far in Xcode:

NSString *ProductListOneString = response;
NSMutableArray *ProductListArray;


bool flag = true;

while (flag) {

//[ProductListArray addObject: [ProductListOneString substringFromIndex:0 ProductListOneString: index(@"_", 0)]];


[ProductListArray addObject: [[ProductListOneString componentsSeparatedByString:@"_"] objectAtIndex:0]];
ProductListOneString = [[ProductListOneString componentsSeparatedByString:@"_"] objectAtIndex:0];

if ([ProductListOneString isEqualToString: @"_"]) {
flag = false;
} else {
ProductListOneString = [ProductListOneString substringFromIndex: 1];//I get a *signal sigabrt* error here
}
}



NSInteger index = 2;
int ArraySize = [ProductListArray count];

NSMutableArray *ProductKeycodes;

while(ArraySize > 0){

[ProductKeycodes addObject: [ProductListArray objectAtIndex: index]];

index = index + 3;
ArraySize = ArraySize - 3;
}

CRD CRD
Answer

You first break up the string into an array of substrings by breaking at "_" and then test to see if the first such substring is an "_" - which it cannot be as the delimiters are not part of the substrings.

Your Android code is iterating to achieve what componentsSeparatedByString: does for you in one call. You can replace the while completely and add the result of componentsSeparatedByString: to your ProductListArray.

BTW start variables with a lowercase letter in Objective-C - notice how the syntax coloring is wrong as you used an uppercase letter.

HTH

Comments