2015-10-16 77 views
0

我有一個返回2結果(我可以看到使用NSLog記錄)的數組(_websites)。無法與NSArrayController綁定NSArray

我想要做的是在NSTableView中顯示那些有3列的2條記錄。我做了大量的嘗試,將我的數組的內容與NSArrayController綁定,沒有任何成功。

這裏是.h文件

#import <Cocoa/Cocoa.h> 
#import "AppDelegate.h" 

@interface CombinedViewController : NSViewController <NSTableViewDataSource> 
@property (nonatomic,strong) NSManagedObjectContext *mObjContext; 
@property AppDelegate *appDelegate; 
@property (strong) IBOutlet NSArrayController *combinedRecordsArrayController; 
@property (nonatomic,strong)NSArray *websites; 
@property (weak) IBOutlet NSTableView *tableView; 

@end 

.m文件代碼:

#import "CombinedViewController.h" 
#import "Website.h" 
#import "Customer.h" 
#import "Hosting.h" 

@interface CombinedViewController() 

@end 

@implementation CombinedViewController 

- (void)viewDidLoad { 

    [super viewDidLoad]; 
    _appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate]; 
    self.mObjContext = _appDelegate.managedObjectContext; 
    [self getCombinedResutls];  

} 

-(NSArray *)getCombinedResutls { 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Website" inManagedObjectContext:self.mObjContext]; 
    [fetchRequest setEntity:entity]; 
    NSError *error = nil; 
    NSArray *fetchedObjects = [self.mObjContext executeFetchRequest:fetchRequest error:&error]; 
    if (fetchedObjects == nil) { 
     NSLog(@"Error:%@",error); 
    } 
    _websites = [_mObjContext executeFetchRequest:fetchRequest error:nil]; 

    for (Website *ws in _websites) { 
     Customer *cust = ws.customerInfo; 
     Hosting *host = ws.hostingInfo; 

     NSLog(@"Website: %@, Customer: %@, Hosting Provider: %@",ws.websiteUrl, cust.customerName, host.hostingProvider); 

    } 

return fetchedObjects; 
} 


@end 

我想學習如何做左右逢源,使用可可綁定和編程,因此任何將不勝感激。帶有一些最新教程的鏈接也將非常受歡迎。

我只是忘了提及...我在控制器內容中綁定NSArrayController與ContentArray,然後我綁定NSTableView與NSArrayController,以及我的表列,但我得到空NSTableView ...沒有錯誤顯示在控制檯上。

回答

1

如果您使用直接iVar訪問 - _websites - 編寫websites屬性的iVar,綁定依賴的KVO通知從不發生。

如果您改爲使用self.websites =或更多明確[self setWebsites: ...,那麼您將觸發KVO通知給陣列控制器,網站屬性的值已更新。

相反,在XIB陣列控制器是未歸檔和viewDidLoad之前綁定到websites,所以在這一點上,是websitesnil。隨後,您永遠不會觸發任何有關websites更改值的KVO通知,因爲您明確避免使用websites訪問者setWebsites,而是使用直接實例變量訪問。所以AC不知道websites發生了變化,表格從未反映websites的任何值,但nil除外。

一般情況下,除非您有足夠的理由這樣做並完全理解您爲什麼這麼做,否則絕對不要使用實例變量來訪問屬性的值。

+0

我改變了_websites與self.websites在我使用它的2行,而是一個空的nstableview,我現在得到錯誤:實體網站是不符合密鑰值的關鍵字「customerName」的密鑰值。還有什麼我應該改變我的代碼? – user2417624

+0

您似乎在您的代碼中使用了customerInfo,而不是customerName – stevesliva

+0

這就是for循環,如果我在那裏使用customerName,則顯示錯誤。我無法看到任何其他地方我有customerInfo。 CustomerInfo是關係的名稱,(一對一) – user2417624

相關問題