代码改变世界
2013-01-18 17:56
三戒1993
阅读(133)
评论()
编辑
收藏
举报
-
先按照网上的教程,建一个简单的带coredata的项目
-
再 添加一个 UserInfo 对象(表)(按照网上的教材,可视化方式添加)
-
-
然后在AppDelegate.m中按如下修改,(只添加了4个方法)
-
-
然后运行,看控制台日志
-
-
-
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
-
{
-
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
-
-
self.window.backgroundColor = [UIColor whiteColor];
-
[self.window makeKeyAndVisible];
-
-
[self addUser];
-
[self gainDatas];
-
-
return YES;
-
}
-
-
-(void)addUser{
-
UserInfo * userInfo = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo"
-
inManagedObjectContext:self.managedObjectContext];
-
userInfo.name = @"dage";
-
userInfo.password = @"password3";
-
NSError *error = nil;
-
if (![self.managedObjectContext save:&error]) {
-
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
-
abort();
-
}
-
-
NSLog(@"add success");
-
-
}
-
-
-(void)gainDatas {
-
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
-
[fetchRequest setEntity:[NSEntityDescription entityForName:@"UserInfo" inManagedObjectContext:self.managedObjectContext]];
-
-
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like[cd]'baobao'"];
-
-
-
NSMutableArray *sortDescriptors = [NSMutableArray array];
-
[sortDescriptors addObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] ];
-
-
[fetchRequest setPredicate:predicate];
-
[fetchRequest setFetchBatchSize:5];
-
[fetchRequest setSortDescriptors:sortDescriptors];
-
[fetchRequest setReturnsObjectsAsFaults:NO];
-
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"name", @"password", nil]];
-
NSError *error = nil;
-
NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
-
if (fetchedItems == nil) {
-
NSLog(@"fetch request resulted in an error %@, %@", error, [error userInfo]);
-
}else {
-
NSLog(@"fetchedItems=%d",fetchedItems.count);
-
for (UserInfo *user in fetchedItems) {
-
NSLog(@"user.authour=%@",user.name);
-
-
-
}
-
}
-
}
-
-
-(void)deleteUser:(id)user{
-
[self.managedObjectContext deleteObject:user];
-
NSError *error = nil;
-
if (![self.managedObjectContext save:&error]) {
-
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
-
abort();
-
}
-
-
NSLog(@"delete success");
-
}
-
-
-(void)updateUser:(UserInfo*)user{
-
user.name = @"baobao";
-
NSError *error = nil;
-
if (![self.managedObjectContext save:&error]) {
-
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
-
abort();
-
}
-
-
NSLog(@"update success");
-
}