Revision: 25500
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at April 1, 2010 02:17 by iswear_wxp
Initial Code
在我们分æžäº†ç¨‹åºä¸»ä»£ç†æ–‡ä»¶ï¼ˆAppDelegate)之åŽï¼Œæˆ‘们先æ¥çœ‹çœ‹ä¸€å¯¹è‡ªåŠ¨ç”Ÿæˆçš„æ–‡ä»¶Event.h/.m
@interface Event : NSManagedObject {}
@property (nonatomic, retain) NSDate *creationDate;
@property (nonatomic, retain) NSNumber *latitude;
@property (nonatomic, retain) NSNumber *longitude;
@end
#import "Event.h"
@implementation Event
@dynamic creationDate;
@dynamic latitude;
@dynamic longitude;
@end
ä»Žä¸Šé¢æˆ‘们能看出æ¥ï¼Œä¸€ä¸ªå®žä½“Event也就会被生æˆä¸€ä¸ªNSManagedObject(被管ç†å¯¹è±¡ï¼‰ï¼Œç„¶åŽä»»ä½•accessorå’Œgetter 都是被动æ€ç”Ÿæˆçš„,我们其实完全ä¸ç”¨æ“任何的心,åªéœ€è¦åœ¨xcdatamodel文件里é¢é…ç½®åŽï¼Œç‚¹å‡»æ·»åŠ æ–‡ä»¶ï¼Œæ·»åŠ NSManagedObject文件,就会看到自动感知的类对象,然åŽç”Ÿæˆå°±å¯ä»¥äº†ã€‚
䏋颿˜¯æ ¹è§†å›¾æŽ§åˆ¶å™¨ï¼Œæ˜¯ä¸€ä¸ªåˆ—表视图(UITableViewController)
#import <CoreLocation/CoreLocation.h>
@interface RootViewController : UITableViewController <CLLocationManagerDelegate> {
//看到是UITableViewControllerçš„å类,由于需è¦ä½¿ç”¨Core Location,
//所以在åŽé¢å±¥è¡Œå…¶protocal
NSMutableArray *eventsArray;
NSManagedObjectContext *managedObjectContext;
//这个被管ç†å¯¹è±¡å†…容器就是我们真æ£å¯¹Core Dataæ•°æ®çš„æ“ä½œå¯¹è±¡
CLLocationManager *locationManager; //用æ¥å¾—到地ç†ä½ç½®çš„Core Location对象
UIBarButtonItem *addButton; //å³ä¸Šè§’çš„æ·»åŠ é”®
}
@property (nonatomic, retain) NSMutableArray *eventsArray;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) UIBarButtonItem *addButton;
- (void)addEvent;
@end
#import "RootViewController.h"
#import "LocationsAppDelegate.h"
#import "Event.h"
@implementation RootViewController
@synthesize eventsArray, managedObjectContext, addButton, locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Locations"; //è®¾ç½®åˆ—è¡¨è§†å›¾çš„æ ‡é¢˜
self.navigationItem.leftBarButtonItem = self.editButtonItem; //导航æ 左边的编辑按钮
addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addEvent)]; //åˆå§‹åŒ–æ·»åŠ æŒ‰é’®ï¼Œ
addButton.enabled = NO; //在Core Locationåˆå§‹åŒ–之å‰å°†å…¶å…³é—
self.navigationItem.rightBarButtonItem = addButton;
//æŠŠè¿™ä¸ªæ·»åŠ æŒ‰é’®æ·»åŠ åˆ°å¯¼èˆªæ å³ä¾§
// å¯åЍCLocation
[[self locationManager] startUpdatingLocation];
//åˆå§‹åŒ–一个“获å–请求â€åˆ°æˆ‘们的实体“Eventâ€
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// 将时间以建立时间排åºï¼Œæœ€æ–°çš„在最上
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
// 执行“获å–â€æ“作,得到一个“å¯å˜æ•°ç»„â€çš„æ‹·è´
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext
executeFetchRequest:request
error:&error] mutableCopy];
if (mutableFetchResults == nil) {
//如果结果为空,在这作错误å“应
}
// å°†å¾—åˆ°çš„æœ¬åœ°æ•°ç»„èµ‹å€¼åˆ°æœ¬ç±»çš„å…¨å±€æ•°ç»„ï¼Œç„¶åŽæ¸…ç†æ— 用的对象
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
}
- (void)viewDidUnload {
// 当视图被å¸è½½åŽï¼Œå°†ä»¥ä¸‹æŒ‡é’ˆç½®ç©º
self.eventsArray = nil;
self.locationManager = nil;
self.addButton = nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// åªæœ‰ä¸€ä¸ªç« 节
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// åœ¨æ•°ç»„é‡Œé¢æœ‰å¤šå°‘个对象,在列表视图就有多少行
return [eventsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ä¸€ä¸ªâ€œæ—¥æœŸæ ¼å¼åŒ–器â€ï¼ˆå‡‘åˆæ˜Žç™½å°±å¥½...)用æ¥ä»¥ç‰¹å®šçš„æ ¼å¼åˆ›å»ºå¾—到的日期
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}
static NSNumberFormatter *numberFormatter = nil;
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:3];
}
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
UITableViewCellStyleSubtitle;
}
// 从数组ä¸å¾—到这个Event对象
Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dateFormatter stringFromDate:[event creationDate]];
NSString *string = [NSString stringWithFormat:@"%@, %@",
[numberFormatter stringFromNumber:[event latitude]],
[numberFormatter stringFromNumber:[event longitude]]];
cell.detailTextLabel.text = string;
return cell;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// åˆ é™¤è¢«æƒ¯ä¾‹å¯¹è±¡åœ¨ç´¢å¼•è·¯å¾„ï¼ˆindex path)
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:eventToDelete];
// 更新数组和列表视图
[eventsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// æäº¤æ›´æ”¹åˆ°Core Data
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
- (void)addEvent {
//如果得ä¸åˆ°ä½ç½®ï¼Œå°±è¿”回.
CLLocation *location = [locationManager location];
if (!location) {
return; }
//建立一个Event实体对象
Event *event = (Event *)[NSEntityDescription
insertNewObjectForEntityForName:@"Event"
inManagedObjectContext:managedObjectContext];
//得到ç»çº¬åº¦ï¼Œç„¶åŽèµ‹å€¼åˆ°event对象去
CLLocationCoordinate2D coordinate = [location coordinate];
[event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]];
[event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]];
// 实例里é¢å¹¶æ²¡æœ‰ä½¿ç”¨CLçš„æ—¶é—´æ ‡ç¾ï¼Œå› 为在模拟器ä¸ä¼šæ˜¯ä¸€æ ·çš„
// [event setCreationDate:[location timestamp]];
[event setCreationDate:[NSDate date]];
//æ‰€ä»¥çŽ°åœ¨ä½¿ç”¨çš„æ˜¯çŽ°åœ¨çš„æ—¶é—´ï¼Œè€Œä¸æ˜¯å¾—到ä½ç½®çš„æ—¶å€™çš„æ—¶é—´
// ä¿å˜æ›´æ”¹
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
// 将新Event放到最上é¢ï¼Œæ‰€ä»¥æ·»åŠ åˆ°0çš„ä½ç½®
// ç„¶åŽæ»šåŠ¨åˆ—è¡¨è§†å›¾åˆ°æœ€ä¸Šé¢ï¼Œå¦‚æžœæ²¡æœ‰é‚£ä¹ˆå¤šçš„æ•°æ®æ˜¯çœ‹ä¸å‡ºæ¥åŒºåˆ«çš„
[eventsArray insertObject:event atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (CLLocationManager *)locationManager {
//自定义的CLocationçš„getter,方便åˆå§‹åŒ–
if (locationManager != nil) {
return locationManager;
}
//åˆå§‹åŒ–CL对象,然åŽè®¾ç½®ç²¾å‡†åº¦ï¼Œç„¶åŽå°†ä»£ç†å¯¹è±¡è®¾ä¸ºæœ¬åœ°
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager setDelegate:self];
return locationManager;
}
//CLocationçš„ä¸€ä¸ªä»£ç†æ–¹æ³•,如果æˆåŠŸå°±å¼€å¯å³ä¾§æ·»åŠ æŒ‰é’®
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
addButton.enabled = YES;
}
//CLocationçš„ä¸€ä¸ªä»£ç†æ–¹æ³•,如果失败了就关é—(disable)å³ä¾§æ·»åŠ æŒ‰é’®
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
addButton.enabled = NO;
}
- (void)dealloc {
//释放对象
[managedObjectContext release];
[eventsArray release];
[locationManager release];
[addButton release];
[super dealloc];
}
@end
从上é¢çš„æºä»£ç ,我们å¯ä»¥çœ‹å‡ºï¼Œ
1,在这里数æ®å¹¶ä¸æ˜¯æ¯æ¬¡éƒ½ç”±NSManagedContext对象得到,而是由一个数组得出。
2,数组是一个å¯å˜æ•°ç»„,由第一次载入的视图的时候从NSManagedContextä¸å¾—到
3,从NSManagedContext对象ä¸å¾—到数æ®éœ€è¦ä½¿ç”¨NSFetchRequestæ¥åˆå§‹åŒ–一个“获å–â€
4ï¼Œæ¯æ¬¡èŽ·å¾—æ–°çš„æ•°æ®çš„æ—¶å€™ï¼ŒåŒæ—¶ä¿å˜åˆ°æ•°ç»„å’ŒNSManagedContextä¸ï¼Œæ·»åŠ åŽéœ€è¦å¯¹æ›´æ”¹è¿›è¡Œæäº¤
Initial URL
http://c.gzl.name/archives/412
Initial Description
Initial Title
CoreData实例分æžå¦ä¹ (2)
Initial Tags
Initial Language
iPhone