私はVCにテキストビューを持っています。nsuserdefaults を使用してこのテキストビューを保存し、後で取得します。VC1 では、保存されたテキストビューを取得し、UITableView に表示します。しかし、アプリを起動すると、インデックス 0 に「null」テキストが自動的に表示されます。
VC:
-(void)save:(id)sender{
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:textView.text forKey:@"savetext"];
[userData1 synchronize];
}
VC1:
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
textArray=[[NSMutableArray alloc]init];
txt=[[UITextView alloc]initWithFrame:CGRectMake(0, 0, 320, 400)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:@"savetext"];
txt.text = [NSString stringWithFormat:@"%@", savedValue];
MyAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// [MyAppDelegate.textArray addObject:txt.text];
if(![MyAppDelegate.textArray containsObject:txt.text]){
[MyAppDelegate.textArray addObject:txt.text];
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:MyAppDelegate.textArray forKey:@"save"];
[userData1 synchronize];
}
[self.view addSubview:txt];
tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 568) style:UITableViewStylePlain];
NSLog(@"Scrolling");
tableView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleRightMargin;
// tableView.contentInset = UIEdgeInsetsMake(0, 0,300, 0); //values passed are - top, left, bottom, right
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];
tableView.contentInset = UIEdgeInsetsMake(0, 0,300, 0);
//self.view = tableView;
[self.view addSubview:tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray* myMutableArrayAgain = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"save"]];
NSLog(@"count is %@",myMutableArrayAgain);
return [myMutableArrayAgain count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableArray* myMutableArrayAgain = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"save"]];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier ];
NSLog(@"cell is %@",cell);
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSLog(@"cell is %@",cell);
}
// Configure the cell...
cell.textLabel.text = [myMutableArrayAgain objectAtIndex:indexPath.row];
[cell.textLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:14]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}