2011年6月5日 星期日

ManagedObjectContext

先在該view controller定義一個
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; 


在<ClassName>AppDelegate.m 中的 - (BOOL)application:didFinishLaunchingWithOptions: 把managedObjectContext帶給viewController的managedObjectContext。如此一來在可以view controller就可以用了。

    rootViewController.managedObjectContext = context;

找出是哪一個Context

    Cost *costEvnet = (Cost *)[NSEntityDescription insertNewObjectForEntityForName:@"Cost" inManagedObjectContext:self.managedObjectContext];
    
設定內容
    [costEvnet setType:@"Food"];
    [costEvnet setMoney:[NSNumber numberWithInt:200]];
    [costEvnet setCostDate:[NSDate date]];
    
存檔
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"RootViewController save Failed.");
    }

建立要求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

執行要求並回傳到Array中
    NSError *error = nil;
    NSMutableArray *objects = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

刪除記錄

        NSManagedObject *eventToDelete = [ self.contextMutableArray objectAtIndex:indexPath.row];
        [self.managedObjectContext deleteObject:eventToDelete];

Custom Table View Cell

  • Command+N: Cocoa Touch -> Object-C class -> UITableViewCell -> [ClassName]
  • Command+N: User Interface -> Empty -> [ClassNameForNib]
  • 可以在ClassNameForNib裡面排版這個Cell要怎麼表示。並連結ClassName裡的IBOutlet


修改 ViewController的  - (UITableViewCell *)tableView: cellForRowAtIndexPath:

    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
    
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        NSLog(@"cell == nil");
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        
        for (id oneObject in nib) {
            if ([oneObject isKindOfClass:[CustomCell class]]) {
                cell = (CustomCell *)oneObject;
                break;
            }
        }

    }


這是因為再還沒有可再利用的顯示格時,他會先從nib載入。以上的nib會回傳一個這個nib內所有的物件陣列。由於Apple並無標準文件告知會由何種順序出現,而且也一直再改變,不得已只好先依此來找到Cell的表示方式。

若有改變到高度的話,就要修改


- (CGFloat)tableView:heightForRowAtIndexPath: 

Navigation Controller

  • 加入 UINavigation 的 instance variable
  • - (BOOL)application: didFinishLaunchingWithOptions: 這個Function中 把要加入的root controller放進來。
  • 放進來要在alloc viewController時要以自己的class命名
  • 最後使用 window addsubview的方式。
  • 可以用self.navigationItem的方式加入button