2011-12-18 2 views
1

저는 Objective C와 iPhone SDK를 점진적으로 배웠습니다. 현재 프로젝트에는 숫자 데이터 (스포츠 데이터)를 저장하는 응용 프로그램을 작성해야합니다. 동일한 목적을 수행하는 여러 개의 앱이 있기 때문에 주로 학습 목적으로 사용됩니다. 어쨌든, 나는 약간의 걸림돌을 때렸다. 내 의도는 테이블에 저장된 플레이어 목록을 가지고 사용자가 추가 플레이어를 추가 할 수있게하는 것입니다.배열 데이터를 Plist에 저장 /로드하려고 시도합니다.

지금은 버튼을 누르면 "Ninjas"가 테이블에 추가됩니다. 또한 테이블에서 삭제 기능을 사용하도록 설정했습니다. 불행히도, 나는 plist에서 데이터를 저장하고로드하는 방법을 알아낼 수 없습니다. 나는 다양한 튜토리얼과 가이드를 따랐지만, 무슨 일이 일어나는지 알 수 없다. 내 의혹은 빈 배열에서 데이터를로드하고 그 배열에 추가하지만 데이터를 포함하는 배열은 plist와는 별도의 배열입니다. 불행히도, 나는 그 이상으로 조금 잃어버린다.

보기를 전환 할 때마다 내 배열의 데이터가 지워집니다. 그러나, 내가 떠나고 돌아올 경우 데이터가 남아 있다는 것을 알았지 만, 상당한 시간 동안 떠난다면 떠나서 아이폰을 다시 시작하는 등의 일은하지 않습니다. 이것은 내가 일하지 않은 앱 절약. 사용자가 실수로 프로그램을 종료 한 경우 iPhone을 데이터에 고정시키는 기능입니까?

바라건대 내가 다소 분명히 설명했다. TL : DR 버전 : 배열에 데이터를 추가하고 plist에 저장 한 다음 배열이 화면에 표시 될 때마다 plist에서 데이터를 다시로드하려고합니다. 아래 코드는이 작업을 시도하지만 성공하지 못합니다.

감사

#import "RootViewController.h" 
#import "NewPlayer.h" 
#import "OptionsMenu.h" 

@implementation RootViewController 
@synthesize createdPlayers; 
@synthesize listOfPlayers; 

-(NSString *) pathOfFile{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentFolder = [paths objectAtIndex:0]; 
    return [documentFolder stringByAppendingFormat:@"myfile.plist"]; 

} 


-(void)applicationWillTerminate:(NSNotification*)notification{ 
    NSMutableArray *array = [[NSMutableArray alloc]init]; 
    [array writeToFile: [self pathOfFile] atomically:YES]; 
} 


- (void)viewDidLoad 
{ 

    NSString *filePath = [self pathOfFile]; 
    if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) { 
     NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; 
     listOfPlayers.array = [array objectAtIndex:0]; 
     [array release]; 

    } 

    UIApplication *app = [UIApplication sharedApplication]; 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app]; 

    [super viewDidLoad]; 
    listOfPlayers = [[NSMutableArray alloc] init]; 

} 


-(IBAction)AddButtonAction:(id)sender{ 
    [listOfPlayers addObject:@"Ninjas"]; 
    [createdPlayers reloadData]; 
} 

-(IBAction)switchView:(id)sender{ 

    OptionsMenu *second = [[OptionsMenu alloc] initWithNibName:nil bundle:nil]; 
    [self presentModalViewController:second animated:YES]; 
} 

-(IBAction)newView:(id)sender{ 
    NewPlayer *second = [[NewPlayer alloc] initWithNibName:nil bundle:nil]; 
    [self presentModalViewController:second animated: YES]; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated 
{ 

    [super viewWillDisappear:animated]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [listOfPlayers count]; 
} 

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    // Configure the cell. 
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15]; 

    cell.textLabel.textColor = [UIColor whiteColor]; 
    cell.textLabel.textAlignment = UITextAlignmentCenter; 

    NSString *cellValue = [listOfPlayers objectAtIndex:indexPath.row]; 
    cell.textLabel.text = cellValue; 

    return cell; 
} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 

     NSLog(@"delete section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]); 
     [listOfPlayers removeObjectAtIndex:[indexPath indexAtPosition:1]]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 

    else if (editingStyle == UITableViewCellEditingStyleInsert) 
    { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
    } 
} 


-(void)tableView:(UITableView *)listOfPlayers moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath{ 
} 

-(void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Relinquish ownership any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. 
    // For example: self.myOutlet = nil; 
} 



- (void)dealloc{ 
    [createdPlayers release]; 
    [listOfPlayers release]; 
    [super dealloc]; 
} 

@end 


#import <UIKit/UIKit.h> 

@interface RootViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { 

    IBOutlet UITableView* createdPlayers; 
    IBOutlet UIButton* superCat; 

    NSMutableArray *listOfPlayers; 

} 

@property(nonatomic, retain) IBOutlet NSObject *listOfPlayers; 

-(NSString *) pathOfFile; 
-(void)applicationWillTerminate:(NSNotification*)notification; 

-(IBAction)AddButtonAction:(id)sender; 

-(IBAction)switchView:(id)sender; 

-(IBAction)newView:(id)sender; 

@property (nonatomic, retain) UITableView* createdPlayers; 


@end 

코드 업데이트 20 년 12 월

는 :

-(NSString *) pathOfFile{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentFolder = [paths objectAtIndex:0]; 
    return [documentFolder stringByAppendingFormat:@"myfile.plist"]; 

} 


-(void)applicationWillTerminate:(NSNotification*)notification 
{ 
    [self.listOfPlayers writeToFile:[self pathOfFile] atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 

} 



- (void)viewDidLoad 
{ 
    self.listOfPlayers = [[NSMutableArray alloc] init]; 

    NSString *filePath = [self pathOfFile]; 
    if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) { 
     NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; 
     self.listOfPlayers = array; 
     [array release]; 

    } 

    UIApplication *app = [UIApplication sharedApplication]; 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app]; 

    [super viewDidLoad]; 


} 
+0

어쩌면 응용 프로그램 대신에 viewwilldisappear가 종료됩니까? 그게 문제를 일으키는 바보 같은 것일 수도 있습니다. btw, plist를 만들기위한 코드를 보았습니다.하지만 어디에서로드합니까? – Armand

답변

0

나는 PLIST를 모른다. 하지만 사용해 볼 수 있습니다 NSData

NSArray *array; 
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array]; 
//Write data 
[data writeToFile:filePath atomically:YES]; 
//Read data 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSData *oldData = [fileManager contentsAtPath:filePath]; 
NSArray *newArray = [NSKeyedUnarchiver unarchiveObjectWithData:oldData] 
0

iOS 프로그래밍의 세계에 오신 것을 환영합니다. 그것은 많은 즐거움을 주지만, 모든 언어로 프로그래밍 할 수있는 것처럼 실망 스러울 수 있습니다. 나는 너의 고통을 느낀다.

내가 볼 가지가 있습니다 :있는 viewDidLoad에서

  1. , 배열 괜찮으로 코드가 파일을 읽을 나타납니다,하지만 당신이하려는 것처럼 다음이 나타납니다 이 배열의 최초의 행만을 listOfPlayers에 할당합니다. 시도해보십시오 :

    self.listOfPlayers = array; 
    
  2. 배열은 배열이며 listOfPlayers도 같습니다. 또한 self를 사용하면 합성 된 setter가 사용되므로 배열을 릴리스 할 때 listOfPlayers를 유지할 수 있습니다.

  3. applicationWillTerminate에서는 파일에 listOfPlayers를 작성하려고하지만 실제로 수행중인 작업은 빈 배열을 할당 및 초기화하고 THAT를 파일에 쓰는 것입니다. 시도 :

    -(void)applicationWillTerminate:(NSNotification*)notification 
    { 
        [self.listOfPlayers writeToFile: [self pathOfFile] atomically:YES]; 
    } 
    

난이 도움이되기를 바랍니다!

+0

내가 만든 변경 사항을 원본 게시글에서 편집했습니다. 그것은 나를 비하하는 오류를 주었고 그래서 나는 것을 업데이트했습니다. NSObject로 무슨 일이 일어나고 있는지가 WriteToFile 문제에 응답하지 않을 수 있습니다. 프로그램은 여전히 ​​실행되지만 사물은 여전히 ​​올바르게 저장되지 않습니다. 나는 계속해서 검색하고 시도 할 것입니다. 나는 편집이나 무언가를 놓쳤을지도 모른다. – Dinoberry

0

당신은 이제까지 그것을 할당하기 전에 listOfPlayers에 액세스하는

if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) { 
    NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; 
    listOfPlayers.array = [array objectAtIndex:0]; 
    . 
    . 

} 
. 
. 
. 
listOfPlayers = [[NSMutableArray alloc] init]; 

당신의 viewDidLoad에 뭔가 잘못이있는 것 같습니다. listOfPlayers.array도 잘못되었습니다.

관련 문제