如何从对象中提取字典

时间:2014-07-21 13:12:32

标签: ios7 xcode5 nsarray nsdictionary

这是我的数据结构

文件InvoiceData.h

#import <Foundation/Foundation.h>
@interface InvoiceData : NSObject

@property (atomic, strong) NSString *invNumber;
@property (atomic, strong) NSString *invDate;
@property (atomic, strong) NSMutableArray *invItems;

@end

文件InvoiceData.m

#import "InvoiceData.h"
@Implementation InvoiceData

@synthesize invNumber
@synthesize invDate
@synthesize invItems;

@end

在Debug中,我的数据看起来像这样

invoiceArray = @"2 Objects"
 [0] = 0xbdbf3e0
   > NSObject
   > invNumber = @"31121-0314"
   > invDate   = @"02/14/2014"
   > invItems = @"2 objects"
     [0] = 2 key/value pairs
        > [0] = @"Tylenol":@"dItem"
        > [1] = @"2" :@"dQty"
     [1] = 2 key/value pairs
        > [0] = @"Advil":@"dItem"
        > [1] = @"4" :@"dQty"
 [1] = 0xbdb3e00
   > NSObject
   > invNumber = @"35521-0614"
   > invDate   = @"06/12/2014"
   > invItems = @"1 object"
     [0] = 2 key/value pairs
        > [0] = @"Tylenol":@"dItem"
        > [1] = @"1" :@"dQty"

这是cellForRowAtIndexPath的代码。使用下面的代码,我没有得到invoiceItemDict的字典。我做错了什么

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"InvoiceItems";
    InvoiceItemsTableViewCell * cell = (InvoiceItemsTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *invoiceItemDict =[((InvoiceData*)[invoiceArray objectAtIndex:indexPath.section]).invItems objectAtIndex:indexPath.row];
    cell.invoiceitem.text = [invoiceItemDict objectForKey:@"dItem"];
    cell.qty.text = [invoiceItemDict objectForKey:@"dQty"];
    return cell;
}

如果,我要在viewDidLoad中加载这样的数据,我将如何访问cellForRowAtIndexPath中的Invoice Item

for (int i=0; i < 1; i++) {
    InvoiceData *theInvData = [[InvoiceData alloc] init];
    theInvData.roNumber = @"31121-0314";
    theInvData.dateIn   = @"02/14/2014";
    theInvData.invItems = [[NSMutableArray alloc] init];
    for (int k=0; k<2; k++) {
        NSMutableDictionary *invItemDetail;
        if (k ==0) {
            invItemDetail = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                     @"dItem" ?: [NSNull null], @"Tylenol",
                                     @"dQty"  ?: [NSNull null], @"2",
                                     nil];
        } else {
            invItemDetail = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                     @"dItem" ?: [NSNull null], @"Advil",
                                     @"dQty"  ?: [NSNull null], @"4",
                                     nil];
        }
        [theInvData.invItems addObject:invItemDetail];
        invItemDetail = nil;
    }
}

0 个答案:

没有答案