- 浏览: 321576 次
- 性别:
- 来自: 深圳
文章分类
最新评论
-
ljl961890233bear:
...
利用MySQL Cluster 7.0 + LVS 搭建高可用环境 -
wang1352083:
$m->listDBs(); 返回的是一个有dbnam ...
MongoDB PHP API 及用法 -
走忽闪953:
...
putty PasswordAuthentication -
jxhgzs001:
很好 很强大,不顶你一下 觉得过意不去啊
cocos2d 的一些实用代码 -
lingtianlan:
我实际测试的结果却和你不一样,调用顺序是awakeFromNi ...
[转]loadView/viewDidLoad/initWithNibName/awakeFromNib/initWithCoder的用法
在我们分析了程序主代理文件(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中,添加后需要对更改进行提交
@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中,添加后需要对更改进行提交
发表评论
-
sprite list 白边
2012-01-17 11:32 828很奇怪的白边问题 就是sprite list!切图会变成白色 ... -
cocos2d 内存整理
2011-12-31 11:29 1498[[CCSpriteFrameCache sharedSp ... -
CCTransitionScene
2011-12-28 19:08 1024//淡入淡出 CCFadTransition *tran = ... -
OpenGL draw base functions
2011-12-28 19:04 1965-(void) draw { CGSize s = [[C ... -
(转)cocos2d的常用动作及效果总结之五:Animation
2011-12-12 15:57 0这一篇是讲一下如何在cocos2d中实现动画。 实现动画的步 ... -
(转)cocos2d的常用动作及效果总结之四:Special Actions
2011-12-12 15:53 1974Special Actions 个人理解包含三部分,一个是函数 ... -
(转)cocos2d的常用动作及效果总结之三:Ease actions
2011-12-12 15:51 6294Ease actions 影响的是动作的时间线性。 举个例子 ... -
cocos2d的常用动作及效果总结之二:Composition actions
2011-12-12 15:49 1933上一篇整理了 basice action 基本动作的部分,这 ... -
(转)cocos2d的常用动作及效果总结之一: Basic actions
2011-12-12 15:47 3581在官方网站上,对cocos2d ... -
xcode 4 Add Existing Framework
2011-11-14 11:52 1245现在的记性十分不好!老是记不住xcode 4如何Add Exi ... -
(转)iphone应用开发:发送短信/邮件/打电话
2011-11-10 10:46 1186+ (void) makeCall:(NSString *)p ... -
cocos2d 添加 原生得空间的类:CCUIViewWrapper 的用法
2011-11-03 11:55 1915UIView *myView = [[[UIView allo ... -
【转】【Cocos2d游戏开发之一】多触点与触屏事件详解(单一监听、事件分发)
2011-09-20 11:46 1399原文地址:http://blog.csdn ... -
cocos2d 的一些实用代码
2011-09-15 10:51 22971.问题描述: 如果我想让一个 sprite 显示3秒钟然后消 ... -
mac 的一些基本操作
2011-09-08 13:34 8111.寻找共享文件: 以前在windows上输入:\\192 ... -
[转]Cocos2D的4个基本概念
2011-09-06 18:35 1813开发cocos2d 应用程序,必须先了解如下4个概念: Sce ... -
(转) iphone 开发常用到的代码
2011-07-12 11:01 2119- (NSString *)URLEncodedString: ... -
iphone 升级到4.3.3 编译出现的问题
2011-05-25 15:46 1813unable to load symbol file: una ... -
iphone sdk 更新
2011-05-25 12:01 1181ipad被升级到4.3.3版本,但是使用device测试的时候 ... -
iphone in-app-purchase 注意的地方
2011-05-24 12:03 2039使用apple in-app-purchase 还是很麻烦! ...
相关推荐
NULL 博文链接:https://wenxin2009.iteye.com/blog/1704930
coredata的demo,包含如何存图片
苹果提供的coredata技术,自己做的小例子,很适用于初学者! 内有帮助文档!
1.一个完整的app,简单完整的展示coredata在swift中的用法。 2.包括操作撤回、取消撤回功能。3.包括监控系统语言修改功能。4.包括coredata与tableview的融合。5.完全是用swift实现,下载后直接xcode即可运行。
CoreData简单使用dome,CoreData简单使用dome,CoreData简单使用dome
coreData数据库操作!~有需要的盆友可以看一下
SQLite,FMDB,CoreData的小的例子。还有一个小的CALyer隐式动画的例子。
示例演示CoreData如何实现添加、删除、查询功能
coredata是iOS系统提供用于对象化管理数据并且持久化的框架,较于FMDB,coredata的优势:第一是CoreData作为苹果提供的原生框架,在内存方法比SQLite有性能上的优势。第二是CoreData操作数据不需要使用SQLite代码,...
使用CoreData开发iPhone手机应用软件的实例教程.pdf
本人闲暇时间所写的关于CoreData的小例子,里面比较详细的注释,偏于初学者使用
CoreData 数据存储
CoreData的使用,相信的代码注释,学习吧,少年
针对CoreData的一个简单封装,可实现基本的插入,删除,查询,更新的功能。
CoreData入门级程序 不看后悔
代码介绍了coreData简单实现sqlite的一些添加 删除 查找功能
本demo是数据持久化的一种CoreData,对CoreData进行了封装,实现了增删改查
高清正版 objc中国 CoreData
iOS研发中数据缓存coreData的使用
iso持久话存储,数据库,CoreData的介绍