Objective C Array Count String Issue - ios

Okay I am new to objective C and am trying hard to learn it on my own with out bother the stacked overflow community to much but it is really quite different then what I'm used to (C++).
But I have come across a issue that I for the life of me can't figure out and I'm sure it's going be something stupid. But I am pulling questions and answers from a website that then will display on my iOS application by using this code.
NSString * GetUrl = [NSString stringWithFormat:#"http://www.mywebpage.com/page.php"];
NSString * GetAllHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:GetUrl] encoding:1 error:nil];
NSString *PullWholeQuestion = [[GetAllHtml componentsSeparatedByString:#"<tr>"] objectAtIndex:1];
NSString *FinishWholeQuestion = [[PullWholeQuestion componentsSeparatedByString:#"</tr>"] objectAtIndex:0];
After I get all of the webpage information I strip down each question and want to make it where it will do a loop process to pull the questions so basically I need to count how many array options there are for the FinishedWholeQuestion variable
I found this snippet online that seemed to work with there example but I cant repeat it
NSArray *stringArray = [NSArray arrayWithObjects:#"1", #"2", nil];
NSLog(#"count = %d", [stringArray count]);

"componentsSeparatedByString" returns an NSArray object, not a single NSString.
An array object can contain zero, one or more NSString objects, depending on the input.
If you change "FinishWholeQuestion" into a NSArray object, you'll likely get a few components (separate by a string).
And now that I'm looking at your code a little more closely, I see you're making an assumption that your array is always valid (and has more than 2 entries, as evidenced by the "objectAtIndex: 1" bit).
You should also change the first character of all your Objective-C variables. Best practices in Objective-C are that the first character of variables should always be lower case.
Like this:
NSString * getUrl = [NSString stringWithFormat:#"http://www.mywebpage.com/page.php"];
NSString * getAllHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:getUrl] encoding: NSUTF8StringEncoding error:nil];
NSArray * allQuestions = [getAllHtml componentsSeparatedByString:#"<tr>"];
if([allQuestions count] > 1)
{
// assuming there is at least two entries in this array
NSString * pullWholeQuestion = [allQuestions objectAtIndex: 1];
if(pullWholeQuestion)
{
NSString *finishWholeQuestion = [[pullWholeQuestion componentsSeparatedByString:#"</tr>"] objectAtIndex:0];
}
}

Related

How to pass Array to SOAP API?

I need to pass this array to SOAP API as a parameter. The back-end guy is new to building APIs (C#/.NET) and I have never implemented this kind of API before. There are 4-5 SO question related to this. But none of them were the solution as per my query.
NSArray *arr = [NSArray arrayWithObjects:#"1",#"2", nil];
NSString *soapURL = #"http://tempuri.org/IService1/addRecord";
NSString *soapBody = [NSString stringWithFormat:#"<addRecord xmlns=\"http://tempuri.org/\">"
"<id>%#</id>"
"<title>%#</title>"
"<record>%#</record>"
"</addRecord> \n” ,#“1”,#“abc", arr ];
NSLog(#"%#",soapBody);
Error:
value in string The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'addRecord'. End element 'record' from namespace 'http://tempuri.org/' expected. Found text '(
1,
2
)'.
One thing I came to know that I cannot pass array directly in to soapBody. What what is the alternative?
The API is working fine at the back-end.
some comments:
NSArray *arr = [NSArray arrayWithObjects:#"1",#"2", nil];
please write instead the modern form:
NSArray *arr = #[#"1",#"2"];
Also, your question is filled with wrong types of quotes (“1”). Make sure to use the regular quotes, i.e. ".
When you use "stringWithFormat" with %# and provide an array, you must understand what you are getting there. let's try:
NSArray *arr = #[#"1",#"2"];
NSString *str = [NSString stringWithFormat:#"<%#>", arr];
NSLog(#"%#", str);
The result is:
<(
1,
2
)>
It means that between your <record> and </record> you inserted two numbers separated by a comma and surrounded by parentheses, plus some \n.
Is this what your server is expecting?
So I am not solving your problem, but you must format your string the right way and verify it using your NSLog command. Hoping it is helping.
EDIT
If for example you need to provide the values of the array within <value>...</value> than you can do this:
NSArray *arr = #[#"1", #"2"];
NSMutableString *mStr = [NSMutableString string];
for (NSString *value in arr) {
[mStr appendFormat:#"<value>%#</value>", value];
}
NSLog(#"<record>%#</record>", mStr);
And the result will be
<record><value>1</value><value>2</value></record>
Finally I resolved this issue with this code:
NSString *soapBody = [NSString stringWithFormat:#"< addRecord xmlns=\"http://tempuri.org/\" xmlns:arr=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" > \n"
"<ID>1</ID>\n"
"<title>ABC</title>\n"
"<record>\n"];
for (int i=0; i<arrRecord.count; i++) {
soapBody = [NSString stringWithFormat:#"%# <arr:int>%#</arr:int>\n",soapBody,arrRecord[i]];
}
soapBody = [NSString stringWithFormat:#"%# </record></addRecord> \n",soapBody];
I needed to define "arr" in the parent node and type of element(int) in the record array.

Separate a string into different Array

I have a string coming from server , i want to show some part of string in a view and rest part of string in other view .
Thanks for help.
i want to get the last word of last line of first view. i have searched ,but nothing seems to help me. If any one can suggest me something i would be glad to him/her.
NSString *fromIndex = [_categoryWiseNews.article substringWithRange:NSMakeRange(0, lastWordOfFirstView)];
i have tried with substringWithRange but with this you have to know the lastWordOfFirstView index number for breaking the string into two parts, for which i have no idea.
I really don't know what it is that you're asking lastWordOfFirstView might make sense to you because it is relevant to the thing you are working on. But to us it means nothing.
You can separate a string into words in an array doing this...
NSString *string = #"Hello world, this is a string";
NSArray *array = [string componentsSeparatedByString:#" "];
// array is now... [#"Hello", #"world,", #"this", #"is", #"a", #"string"];
Then you can get the last word from it...
NSString *lastWord = [array lastObject];
Use this to get the last word from a sentence:
NSString *lastWord = [[fullSentenceString componentsSeparatedByString:#" "] lastObject];

Unusual stringWithFormat: argument

I apologize if this is a noob question.
I have been following this tutorial about mapkit and I stumbled on this line of code
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
The reason this is unusual at least to me is that it is missing the nsstring that has the %# flags in it. The tutorial claims that we are adding the latitude and longitude information into the json.
But when I print out formatString and json, the output is identical.
I have never seen nsstrings used in this way before. Is there a hidden variable that is getting set?
Can someone explain to me how this nsstring object (named json) contains those 4 arguments?
Someplace else in the code, formatString must be defined something like this:
NSString *formatString = #"latitude=%f, longitude=%f, %f = half the number of meters in a mile";
Make sure your test looks like this:
NSLog(#"the format is %# and the json is %#", formatString, json);
They shouldn't look the same. The only way they would look the same is if format string doesn't refer to any format specifiers, like this:
NSString *formatString = #"I'm a silly format with no percent format specifiers";
Here's a good intro on the topic from Apple.
That formatString actually contains the %#'s. It might be like this:
NSString *formatString = #"lat: %f | lon: %f | half-meters-per-mile: %f";
NSString *json = [NSString stringWithFormat:formatString,
centerLocation.latitude,
centerLocation.longitude,
0.5 * METERS_PER_MILE];
(note that the substitutions (%f) might not be correct, I'm guessing)
As for how it contains those four arguments, everything after the first one are values that you want added into the string. The first one is a string that says where to put those values.
If you check the tutorial, following line of code is written above what you have posted-
NSString *jsonFile = [[NSBundle mainBundle] pathForResource:#"command" ofType:#"json"];
NSString *formatString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];
From here the format string is created, this file will be available in the resources folder of your tutorial.

Interrogating an NSArray that appears to have a null entry

I have an iPad app that links to an SQL database to retrieve information in the following way:
NSString *strGetCodeUrl = [NSString stringWithFormat:#"%#", #"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
This works when there is a device that matches and it retrieves the required information. However if there is not a match it returns
("")
The array however appears to have one record. Ideally I would like to stop this from happening and for the array to be empty if there is no match. Alternatively (although not very tidy) I could check the length of the entry at index 0 but I am struggling with this method.
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ( [deviceCode length] == 0)
{
device does not exist
}
Any advice gratefully received.
What about this:
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ([deviceCode isEqualToString:#""])
{
device does not exist
}
I don't think you can tell the init method to leave out empty strings...
However, you can do this:
NSString *strGetCodeUrl = [NSString stringWithFormat:#"%#", #"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
[deviceArray removeObject:#""];
Which also isn't as tidy as perhaps you were hoping for, but it will remove all empty strings. But at least its just 1 line of code as opposed to about 3 for the if
Per the documentation:
Removes all occurrences in the array of a given object.

How to append NSMutable strings into a UILabel

This is my first question to Stack Overflow. I have been using this site for a while and have used it's resources to figure out answers to my programming questions but I'm afraid I can't find the answer I'm looking for this time.
I've created these five strings:
//List five items from the book and turn them into strings
//1 Josh the Trucker
NSString *stringJosh = #"Josh the Trucker";
//2 The Witch from the Remote Town
NSString *stringWitch = #"The Witch from the Remote Town";
//3 Accepting the curse rules "Willingly and Knowingly"
NSString *stringRules = #"Accepting the curse rules, --Willingly and Knowingly--";
//4 Josh's time left to live--Five Days Alive Permitted
NSString *stringFiveDays = #"Josh's time left to live--Five Days Alive Permitted";
//5 The Fire Demon Elelmental
NSString *stringDemon = #"The Fire Demon Elelmental";
Then, I've put them in an array:
//Create an array of five items from the book
NSArray *itemsArray = [[NSArray alloc] initWithObjects:
stringJosh,
stringWitch,
stringRules,
stringFiveDays,
stringDemon,
nil];
Then, I created this mutable string where I need to loop through the array and append the items to a UIlabel.
NSMutableString *itemsString = [[NSMutableString alloc] initWithString:
#"itemsArray"];
Here's the loop, which displays the items in the console log.
for (int i=0; i<5; i++)
{
NSLog(#"Book Item %d=%#", i, itemsArray[i]);
}
My question is, how do I append these items into the UIlabel?
These functions are in my appledelegate.
In my viewDidAppear function (flipsideViewController) I have:
label8.text =""----thats where the looped info needs to go.
How do I do this?
I feel I need to put them together and append where the NSLog should be...but how do I transfer that info to the textlabel?
I hope I explained myself.
We haven't done ANY append examples, I guess this is where I need to get answers from the "wild"
This is the wildest coding environment I know so I'm hoping I can find some direction here.
Thanks for taking a look!
Once you have all your strings that you want to concatenate in NSArray you can combine them with single call (with whatever separator you want):
NSString *combinedString = [itemsArray componentsJoinedByString:#" "];
If you need more complex logic you can use NSMutableString to create result you want while iterating array, i.e.:
NSMutableString *combinedString = [NSMutableString string];
[itemsArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
[combinedString appendFormat:#"Book Item %d=%# ", idx, obj];
}];
Note also that it is better to iterate through collections using fast enumeration or block enumeration rather than using plain index-based for loop.
NSMutableString *labelText = [NSMutableString string];
int i = 0;
for (NSString *item in itemsArray)
[labelText appendFormat:#"Book Item %d=%#\n", i++, item];
label8.text = labelText;
DO this
UILabel *mainlabel;
mainlabel.text = [origText stringByAppendingString:get];
Add your text to mainlabel.. orig text is mutable string or else in forloop just append array object at index text to label.put above line of code in forloop

Resources