我创建了一个名为House的实体。该实体有两个属性:street(类型为string)和numOfStories(类型为整数32)。我能够在AppDelegate.m didFinishLaunchingWithOptions方法中成功保存和NSLog数据。但是,当我尝试制作2个文本字段并显示用户的输入,并按下要保存的按钮时,结果是SIGABRT。
以下是我在MainViewController.m中使用的所有代码:
- (BOOL)createNewHouseWithStreet:(NSString *)paramStreet numOfStories: (NSUInteger)paramNumOfStories
{
BOOL result = NO;
if ([paramStreet length] == 0)
{
NSLog(@"Street name is mandatory");
return NO;
}
House *newHouse = [NSEntityDescription insertNewObjectForEntityForName:@"House" inManagedObjectContext:self.managedObjectContext];
if (newHouse == nil)
{
NSLog(@"Failed to create the new House");
return NO;
}
newHouse.street = paramStreet;
newHouse.numOfStories = @(paramNumOfStories);
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError])
{
return YES;
}
else
{
NSLog(@"Failed the save the new House. Error = %@", savingError);
}
return result;
}
以下我有
- (IBAction)save:(id)sender {
[self createNewHouseWithStreet:@"10 WYOMING" numOfStories:2];
[self createNewHouseWithStreet:@"6 WYOMING" numOfStories:3];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"House"];
NSError *requestError = nil;
NSArray *houses = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
if ([houses count] > 0)
{
NSUInteger counter = 1;
for (House *thisHouse in houses)
{
NSLog(@"House %lu Street Name = %@", (unsigned long)counter, thisHouse.street);
NSLog(@"House %lu number of stories = %ld", (unsigned long)counter, (unsigned long)[thisHouse.numOfStories unsignedIntegerValue]);
counter++;
}
}
else
{
NSLog(@"Could not find any House entities in the context.");
}
}
所以奇怪的是,每当我点击保存按钮时,这个代码最终导致sigabrt,但是当我将save方法中的代码放入我的AppDelegate.m didFinishLaunchingWithOptions方法时,它的效果很好。
感谢所有帮助,谢谢。