- 一個簡單的例子,主要練習數據的永久存儲和數組排序 ,用到了一些東西,貼一部分關鍵代碼出來
- 後面給出完整的附件,把1.plist 添加到模擬器的目錄去。
//讀取文件路徑sql
- -(NSString *)dataFilePath
- {
- NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- //NSLog(@"======path======%@",paths);
- NSString *documentsDirectory=[paths objectAtIndex:0];
- //NSLog(@"%@",documentsDirectory);
- return[documentsDirectory stringByAppendingPathComponent:@"1.plist"];
- }
數組ide
- //從plist中讀取數據
- NSString *path =[self dataFilePath];
- NSMutableArray *array=[[NSMutableArray alloc] initWithContentsOfFile:path];
- self.recordsArray=array;
- [array release];
- -(void) addrecords:(id)sender
- {
- //獲取填寫內容
- NSString* titletext=inputTextField.text;
- //獲取當前時間
- NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateFormat:@"YY年MM月dd日HH點:mm分:ss秒"];
- NSString* result = [dateFormatter stringFromDate:[NSDate date]];
- [dateFormatter release];
- dateFormatter=nil;
- NSMutableDictionary *newdictionary=[[NSMutableDictionary alloc]init];
- [newdictionary setObject:titletext forKey:@"content"];
- [newdictionary setObject:result forKey:@"datetime"];
- /* 在數組的末尾附加*/
- [self.recordsArray addObject:newdictionary];
- /* save */
- BOOL success = [self.recordsArray writeToFile:[self dataFilePath] atomically:NO];
- NSLog(@"success = %d",success);
- /* reload date */
- [self.recordsArray removeAllObjects];
- NSString *path =[self dataFilePath];
- NSLog(@"path = %@",path);
- NSMutableArray *tempMutableArray = [NSMutableArray arrayWithContentsOfFile:path];
- [self.recordsArray addObjectsFromArray:tempMutableArray];
- NSLog(@"self.recordsArray = %@",self.recordsArray);
- inputTextField.text=@"";
- [recordsTableView reloadData];
- }
- -(void) sortByName
- {
- NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"content" ascending:YES];
- self. recordsArray = [self.recordsArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
- [self.recordsArray writeToFile:[self dataFilePath] atomically:NO];
- NSString *path =[self dataFilePath];
- NSMutableArray *array=[[NSMutableArray alloc] initWithContentsOfFile:path];
- self.recordsArray=array;
- [array release];
- [recordsTableView reloadData];
- }