0

I have a feeling this will be too wordy, but I'll do my best. My app has quotes built-in that change each day. Some of them are over 140 characters, but I would like to be able to share via Twitter, so I need a way to get the count, and if over 140, edit it. What I have so far is:

int maxChars = 140;
        int charsLeft = maxChars - [label1.text length];

        NSString *removed = [label1.text substringToIndex:[label1.text length] -  charsLeft];


        TWTweetComposeViewController* twc = [[TWTweetComposeViewController alloc] init];
        [twc setInitialText:removed];
        [self presentModalViewController:twc animated:YES];

Where label1 is the UILabel that shows the quote. This is throwing an error on quotes over 140 characters

[__NSCFString substringToIndex:]: Range or index out of bounds'

Any thoughts? One other thing I was thinking. Each quote ends with

" - Person who said it

I was thinking I could get the character count, remove the excess characters + 3 and insert an ... before the -. How could I go about doing this, or at least fix my existing code?

user717452
  • 33
  • 14
  • 73
  • 149

1 Answers1

1

Well, just imagine your code with a label that has 10 characters in it.

 int maxChars = 140;

 int charsLeft = maxChars - [label1.text length];

 NSString *removed = [label1.text substringToIndex:[label1.text length] -  charsLeft];

becomes

 int charsLeft = 140 - 10; //charsLeft = 130

 NSString *removed = [label1.text substringToIndex:10 -  130];

This would tell SubstringToIndex to get the characters from 0 to -120, which doesn't make very much sense.

It might be tricky to split your string to isolate the author of the quote because both quotes and author names might include hyphens. If you want to try it anyway, you could do something like one of the answers to this spring-parsing question suggest (http://stackoverflow.com/questions/2166809/number-of-occurrences-of-a-substring-in-an-nsstring) for the string @" - ", and try and isolate the last instance.

Dan Carlson
  • 996
  • 1
  • 12
  • 18
  • in my case I would only be running this code if the length of label1.text is > 140. That way all the short ones would just quote the entire text to Twitter. I do understand what you are saying though about how I have the substring code setup going in the wrong way. Also, in my code there will only be one -, and none of the names include hyphens. Could you point me in a direction to get the difference of the label1.text.length and 140, and remove that many characters (+3) of the characters directly in front of the -? – user717452 Aug 03 '12 at 21:46