Memory optimization when assigning NSString to UILabel text - ios

In my view, I have a UILabel which text property is updated every second.
- (void)updateLabelWithValue:(NSInteger)value
{
self.label.text = [NSString stringWithFormat:#"%i", value];
}
Isn't this costly memory wise? It creates a new NSString every time. Is there a way to just have one NSString instance and update its text?
Thanks

You're worrying too much about a very very minor optimization. Yes, you're creating a new instance of NSString on every pass, but you're also destroying the old one, so in essence you're replacing the string.

Related

NSArray with UI objects (Performance)

I have a NSArray (actually is a mutable array) with a UIWebView object in each index. I use this array to populate cell in a UITableView. I use a for loop to initialize each object in the array as following:
for (int i = 0; i < [self.events count]; i++) {
[self.uiWebViewArray addObject:[[UIWebView alloc] init]];
[[self.uiWebViewArray objectAtIndex:i] setUserInteractionEnabled:NO];
[[self.uiWebViewArray objectAtIndex:i] loadHTMLString:HTMLContent baseURL:nil];
}
At this point I am not populating the UITableViewCells yet.
Although it works, I think that it a terrible approach. Performance goes down when I increase the number of cell. At some point, it is possible to the user note the latency.
I also tried to populate each cell directly with a UIWebView but it is basically the same thing.
Does anyone have a suggestion to solve the problem of populate UITableViewCell with UIWebView objects in a efficient way?
A really appreciate any help.
The problem is not the array, is the webview that is really slow and memory hugry.
If you want to display HTML text with basic CSS and you are deploying >= iOS7, you should use NSAttributeString and that method:
NSDictionary *importParams = #{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding) };
NSError *error = nil;
NSData *stringData = [HTML dataUsingEncoding:NSUTF8StringEncoding] ;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:stringData options:importParams documentAttributes:NULL error:&error];
Or you can use third party libraries DTCoreText is one of them.
I think using a custom cell with a Web View inside it will be the better. Although whole concept of Web View inside a table view is weird.
Inside cellForRowAtIndexPath you would need to do something like:
[cell.webView loadHTMLString:HTMLContent baseURL:nil];
The main advantage of Table View is that the number of actual UITableViewCell instances created in memory are far less than total number of logical cells/rows. Actually, in usual cases Table View only creates cells needed to fill the frame, plus few extra.
So using custom table view cell with Web View inside is way better approach memory wise, but as I said whole idea is a bit weird.

How Receive data from Label, while you have the name of that label in String

I am new in IOS Dev, want to receive text data from one label among many labels, but i have just a name of label in String type variable.
NSString *tag = #"lbl_11";
NSString *recieved_label_data = tag.text;
If the label is stored in a property, you could just use KVC. It can also find ivars in certain situations. Something like this:
UILabel *tagLabel = [self valueForKey:tag];
NSString *recieved_label_data = tagLabel.text;

iOS: Column formatting for NSString not working in UITextView?

I'm working on an iPad app and I need to be able to format some output on the screen in a columnar format. This was similar to my question:
How can I use the \t [tab] operator to format a NSString in columns?
and I used that solution, unfortunately I'm not seeing the same results. My code is as follows:
NSString* titleColumn = [[NSString stringWithFormat:#"%#", displayName] stringByPaddingToLength:25 withString:#" " startingAtIndex:0];
NSString* serializedValue = [[NSMutableString alloc] init];
NSString* valueAsString = [NSString stringWithFormat:#"%.03f", value];
serializedValue = [serializedValue stringByAppendingFormat:#"%#%#", titleColumn, valueAsString];
When logging the items in the console, they are properly aligned, however, when plugging them into a UITextView, they are misaligned. This is how I'm sticking them in the text view:
NSMutableString* displayString = [[NSMutableString alloc] initWithString:#""];
for (NSString* entry in textToDisplay)
{
NSLog(#"%#", entry);
[displayString appendString:entry];
[displayString appendString:#"\n"];
}
[self.fTextPanel setText:displayString];
Any ideas on what I'm doing wrong?
EDIT:
In the log, it looks like this:
Inclination 0.000
Version 0.000
Inferior/Superior 0.000
Anterior/Posterior 0.500
And the UITextView version looks like this: http://imgur.com/vrUzybP,OYxGVd8
The reason for misaligned is the different width for each character. The best way for displaying this type of information is by using UITableView, You can use title and subTitle field for displaying or you can design a custom UITableView.
the reason is because when drawing charachters (glymphs), each character will have different widths,i.e character small c and big C will take different widths for drawing , so it wont work. Even though there are two strings with equal lengths but different characters, the drawing text will have different widths.
What i would suggest you for this is to have two textViews side by side, render titles in one textVIew and values in the next TextView.
If the number of titles is large and if you enable scrolling in textVIews, use delegate Methods of UIScrollView, and when scrollHappens in either of them, set the contentOffset of the other to make it look like single TextView.
Hope this helps.

Replace lines of text in iOS

I am needing to replace a line of text in code on my iOS app, however the lines that need to be replaced in the particular NSString will be different for different entries on the XML that is being parsed.
For example, I need to replace 129727-the-cave.mp3 with 129727.jpg.
However, I can't just tell it to replace -the-cave.mp3, because some instances of the string will have a different number and title of mp3. I think the next line is:
129838-my-song.mp3.
So, basically, I need a way to find everything from the first hyphen through mp3 and replace it, no matter what the text is?
Try this:
NSString *original = #"129727-the-cave.mp3";
NSString *sub = [original substringToIndex:[original rangeOfString:#"-"].location];
NSString *finalString = [sub stringByAppendingString:#".jpg"];
NSLog(#"finalString: %#", finalString);

Change size of text in UITextView based on content of NSString

I am trying to load a UITextView with content from instances of a NSManagedObject subclass (verses in a Bible reader app).
My UITextView is loaded by iterating through the verses in a selected chapter and appending each consecutive verse.
NSArray *selectedVerses = [[Store sharedStore] versesForBookName:selectedBook
ChapterNumber:selectedChapterNum];
displayString = #"";
for (Verse *v in selectedVerses) {
NSMutableString *addedString =
[NSMutableString stringWithFormat:#"%d %#", [v versenum], [v verse]];
displayString = [NSMutableString stringWithFormat:#"%# %#", addedString, displayString];
}
NSString *title = [NSString stringWithFormat:#"%# %#", selectedBook, selectedChapter];
[self setTitle:title];
[[self readerTextView] setNeedsDisplay];
[[self readerTextView] setText:displayString];
The above code generates the correct view, but only allows for one size of text for the entire UITextView.
I would like to have the verse number that precedes each verse to be a smaller size font than its verse, but have not found a way to make it work. I've been reading through the documentation, and it seems that this should be possible with TextKit and CoreText through the use of attributed strings, but I can't seem to get this to compile.
I do not want to load the view as a UIWebView.
Any suggestions for this are greatly appreciated.
You're looking for NSAttributedString and NSMutableAttributedString. You should read Introduction to Attributed String Programming Guide. They're generally like normal strings, but additionally contain attributes with ranges to which they apply. One more method that would be helpful to you is:
[self readerTextView].attributedText = yourAttributedString;
If you have some specific problems with attributed strings, please post your code.

Resources