Can I optimize this at all?
I'm working on an iOS app and I'm using the following code for one of my tables to return the number of rows in a particular section:
return [[kSettings arrayForKey:@"views"] count];
Is th开发者_JS百科ere any other way to write that line of code so that it is more memory efficient?
EDIT:
kSettings
= NSUserDefaults standardUserDefaults
.
Is there any way to rewrite my line of code so that whatever memory it occupies is released sooner than it is released now?
Well, the first thing that comes to my mind is "Why are you fetching the array from NSUserDefaults
every single time -tableView:numberOfRowsInSection:
is invoked?"
Store a pointer reference to this array in your UIViewController
subclass like this:
@interface YourViewController : UITableViewController {
NSArray *views;
}
@property (nonatomic) NSArray *views;
- (void) reload:(BOOL) reloadTable;
//...
@end
@implementation YourViewController
@synthesize views;
- (void) reload:(BOOL) reloadTable {
[self setViews:[NSUserDefaults arrayForKey:@"views"]];
if(reloadTable)
[[self tableView] reloadData];
}
- (void) viewDidLoad {
[super viewDidLoad];
//...
[self reload:NO];
}
- (NSInteger) tableView:(UITableView *) table numberOfRowsInSection:(NSInteger) section {
return [[self views] count];
}
//...
@end
When you need to fully reload the table's data, just invoke [self reload:YES]
.
The way that this approach helps you is because it only re-fetches the data from NSUserDefaults
when you invoke -reload:
, which cuts down on the amount of times NSUserDefaults
is accessed.
Does it need to be more performant? Always remember the first two rules of optimization:
- Don't do it
- (For experts only) Don't do it yet.
Specifically, if the application is running slowly, it's important to figure out where, exactly, the slowdown is occurring. It never seems to be in the place you think it is, so you have to profile and find out for sure. Investigate Instruments.
Just saying. :-)
精彩评论