gpt4 book ai didi

ios - 在代码中将变量保存到 CoreData 实体 - Objective-C/XCode

转载 作者:行者123 更新时间:2023-11-29 02:09:08 28 4
gpt4 key购买 nike

所以,我有一个非常简单的应用程序来学习 Obj-C,其中用户生成一个分数,然后我想将该分数发布到某种“用户排行榜”。

我正在做的事情1. 生成分数2.移动到排行榜 View Controller 并将分数传递给新的 View Controller 3. 将分数添加到临时数组中。

现在,我已经在 CoreData 中创建了一个 Scores 实体,但我以前从未使用过 CoreData,所以我对如何使用它有点困惑。

I've added the "Scores" entity to my CoreData file here

理想情况下,我想要做的不是将 scoreToBeAddedString 保存到数组中,而是将其添加到 Scores 实体中。

我尝试使用此调用,但出现了一堆错误。

CoreDataAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSManagedObject *newScore;
newScore = [NSEntityDescription
insertNewObjectForEntityForName:@"Scores"
inManagedObjectContext:context];
[newScore setValue: _scoreToBeAddedAsString forKey:@"score"];
NSError *error;
[context save:&error];

错误:1. 使用未声明的标识符:'CoreDataAppDelegate2. 使用未声明的标识符:'appDelegate

这是我的 LeaderboardViewController.m 文件。

#import "LeaderboardViewController.h"

@interface LeaderboardViewController ()

@end

@implementation LeaderboardViewController

{
NSMutableArray *scores;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];

//Convert the scoreToBeAdded int to a string

NSNumber *anumber = [NSNumber numberWithInteger:_scoreToBeAdded];

NSString *scoreToAddAsString = [anumber stringValue];

//[scores addObject:scoreToAddAsString]; //This is where I was adding the score to the array, but I want to get rid of this solution, so I can persist the data.

//TODO: Add the scoreToAddAsString to the "Scores" entity in CoreData.

NSLog(@"Leaderboard loaded w new score to add %i", _scoreToBeAdded);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [scores count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

cell.textLabel.text = [scores objectAtIndex:indexPath.row];
return cell;
}

最佳答案

添加#import <CoreData/CoreData.h>在你的LeaderboardViewController.h文件。

添加#import "CoreDataAppDelegate.h"在你的LeaderboardViewController.m文件。

关于ios - 在代码中将变量保存到 CoreData 实体 - Objective-C/XCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470631/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com