如果你的數據結構變得太複雜,你應該考慮存儲的另一種方法。
您可能會忘記使用NSDictionary
,其中Key是書籤的名稱,值是書籤地址。
{
"Google" = "http://google.com"
}
當你加載您應將數據源搶字典從NSUserDefaults
self.bookmarks = [[userDefaults dictionaryForKey:URDictionaryKey] mutableCopy];
爲了使您的表格,以便你可以創建一個排序的字典鍵的NSArray
。
self.bookmarkKeys = [[self.bookmarks allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
爲了您的數據源方法,您使用類似
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return [self.bookmarkKeys count];
}
對於單元配置你使用這樣的:如果用戶在表中刪除行,你會
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSString *title = [self.bookmarkKeys objectAtIndex:indexPath.row];
cell.textLabel.text = title;
cell.detailTextLabel.text = [self.bookmarks objectForKey:title];
return cell;
}
做類似的事情:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *key = [self.bookmarkKeys objectAtIndex:indexPath.row];
[self.bookmarks removeObjectForKey:key];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.bookmarks forKey:URDictionaryKey];
[defaults synchronize];
}
}
更新
你可能會需要使用NSMutableDictionary它是NSDictionary子類,所以在看文檔兩個將有助於你的理解。
在這種情況下,你將被空可變字典開始
self.bookmarks = [NSMutableDictionary dictionary];
然後,當用戶添加書籤您使用的名稱爲key
和目標爲value
它添加到字典
[self.bookmarks setObject:@"http://google.com" forKey:@"Google"];
'NSArray'很好的堅持'NSUserDefaults'。 – 2012-03-05 01:15:38
太棒了!只是..你將如何自動命名數組的每個部分? – JTApps 2012-03-05 01:16:59