如何从.plist获取数据并在tableview

时间:2017-07-13 16:07:31

标签: ios objective-c uitableview

viewDidLoad 方法

   array=[NSMutableArray array];
   dict=[NSDictionary dictionaryWithObjectsAndKeys:@"12.00",@"Tomato"];
   [array addObject:dict];

   dict1=[NSDictionary dictionaryWithObjectsAndKeys:@"75.00",@"Cauliflower"];
   [array addObject:dict1];

问题是我不知道如何将它返回给我的表格视图

enter image description here

注意:我正在使用objective-c

2 个答案:

答案 0 :(得分:2)

我有一个这样的实现:

Swift 3.1

class whatever {
        let plistsource:String = Bundle.main.path(forResource: "plist_name_here", ofType: "plist")!
        var plistData:NSMutableArray?
   ...
        override func viewDidLoad() {
            super.viewDidLoad()
            plistData = NSMutableArray(contentsOfFile: plistSource)
        }
   ... 
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      ...
        cell.some_lable.text = (plistData!.object(at: (indexPath as NSIndexPath).row) as AnyObject).object(forKey: "plist_key") as? String
       // this is all old code, can probably be cleaned up
      ...
        }
}

<强>目标C

@interface myClass : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate> {
...
@property (strong, nonatomic) NSMutableArray *plistData;
...
@end

@implementation myClass
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *plistSource = [[NSBundle mainBundle]pathForResource:@"plist_name_here" ofType:@"plist"];
    plistDataData=[[NSMutableArray alloc]initWithContentsOfFile:path];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    cell.some_label.text = [[[plistData objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]objectForKey:@"plist_key"];
    ...
}
@end

答案 1 :(得分:1)

你可以获得这样的数据。

@interface ViewController ()
{
    NSMutableArray *arrData;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Values" ofType:@"plist"]];
arrData = [dictionary objectForKey:@"KeyName"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@",[arrData objectAtIndex:indexPath.row]];
return cell;
}