Reputation: 58097
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 there 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?
Upvotes: 1
Views: 208
Reputation: 163288
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.
Upvotes: 2
Reputation: 16888
Does it need to be more performant? Always remember the first two rules of optimization:
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. :-)
Upvotes: 2