2013-11-12 3 views
0

Дело в том. Я хочу отображать каждый объект в представлении таблицы, а не в подтипах, поэтому в этом случае. 123. Я не могу понять, как отобразить этот элемент ... также. то, как он сохраняет plist, теперь он перезаписывает plist. поскольку он свежий, созданный каждый раз, когда я иду добавить , я следил за черепахами в Интернете и здесь, когда переполнение стека. но никто, кажется, не приближается к тому, что я хочу делать.Просмотреть данные plist в UITableView

plist

MainTableViewController.h

{ 
NSMutableDictionary *arrayD; 
} 

MainTableViewController.m

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 


// Property List.plist code 
//Gets paths from root direcory. 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
//Get documents path. 
NSString *documentsPath = [paths objectAtIndex:0]; 

//Get the path to our PList file. 
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Servers.plist"]; 

//Check to see if Property List.plist exists in documents. 
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]){ 
    [[NSFileManager defaultManager]copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"Servers" ofType:@"plist"] toPath:plistPath error:nil]; 
    //If not in documents, get property list from main bundle. 
//  plistPath = [[NSBundle mainBundle] pathForResource:@"Servers" ofType:@"plist"]; 

} 

//Read property list into memory as an NSData object. 
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 

NSString *errorDesc = nil; 

NSPropertyListFormat format; 

//convert static property list into dictionary object. 
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; 

    if (!temp){ 
     NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); 
      } 

    //Display values. 
NSMutableDictionary *dictinoary =[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; 

tableData = [dictinoary objectForKey:@"Hostname"]; 
NSLog(@"Count: %i", [arrayD count]); 

}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 

    { 
    static NSString *cellIdentifier = @"Hostname"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

if (cell == nil) { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

} 

cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; 

return cell; 

}

AddServerViewController.m

- (IBAction)SaveData:(id)sender { 
//Get paths from root direcory. 
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
//Get documents path. 
NSString *documentsPath = [paths objectAtIndex:0]; 

//Get the path to our PList file. 
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Servers.plist"]; 

//Set the variables to the values in the text fields. 
hostName = hostEntered.text; 
portNumber = portEntered.text; 
userName = userNameEntered.text; 
passWord = passWordEntered.text; 

NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; 
NSMutableDictionary *data; 
data = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects: hostName, portNumber, userName, passWord, nil]          forKeys:[NSArray arrayWithObjects:@"Hostname", @"Port", @"Username", @"Password", nil]]; 
[rootObj setObject:data forKey:hostName]; 


NSString *error = nil; 

//Create NSData from dictionary. 
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; 

//Check is plistData exists. 
if(plistData){ 

    //Write plistData to our Properity List.plist file. 
    [plistData writeToFile:plistPath atomically:YES]; 

} 
else{ 
    NSLog(@"Error in saveData: %@", error); 
} 

}

ответ

1

В каждом словаре есть метод allKeys, который возвращает массив с ... всеми ключами. Если вы сделаете то, что сказал Питер, а затем вы можете просто заполнить таблицуView allKeys

+0

Я не понимаю, что это все. не могли бы вы привести пример? – KennyVB

+0

понял это ... как всегда, когда я делаю tableData = [dictinoary allKeys]; он говорит: несовместимые типы указателей, назначающие NSMutableArray из Nsarray. как это исправить? – KennyVB

+0

'NSArray * myArray = [yourDictionary allKeys];' тогда вы можете использовать myArray для заполнения всех ключей в вашем представлении таблицы. Я не уверен, хотя если это то, что вам нужно – Astri

0

Прости меня, если я неправильно понял ваш вопрос, но было сделано следующее после воссоздания вашей PLIST:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Sample List" ofType:@"plist"]; 
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:path]; 

NSLog(@"Plist dict %@", [plistDict objectForKey:@"123"]); 

Это выведет:

Plist dict { 
    Hostname = 123; 
    Password = 123; 
    Port = 123; 
    Username = 123; 
} 

Это то, что вы искали? Если нет, вам нужно немного больше узнать о том, что именно вы ищете.

+0

Я хочу просмотреть имя хоста в моем uitableview и только имя хоста .., но если бы он работал правильно, у него было бы еще несколько записей, имя хоста для каждой записи в plist – KennyVB

+0

На основании приведенного выше примера вы просто выполните '[[plistDict objectForKey: @" 123 "] objectForKey: @" Hostname "]' –

+0

, который работает. но что, если это называется чем-то другим? то мне нужно будет каждый раз менять код. а там более разумный способ? скажем, есть 2 записи один с 123 и 456, поэтому без изменения кода, но сделать его общим, чтобы он отображал имя хоста этих двух. возможно или мне нужно изменить код? – KennyVB

Смежные вопросы