xcode 整数转 NSInteger 并保存到核心数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8101715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer to NSInteger And Save To Core Data
提问by Ahan Malhotra
I have a integer named marbles, and am trying to save it into an array using the following code:
我有一个名为弹珠的整数,并尝试使用以下代码将其保存到数组中:
[records setValue:marbles forKey:@"marbles"];
With this code, I get the warning:
使用此代码,我收到警告:
warning: Semantic Issue: Incompatible integer to pointer conversion sending 'int' to parameter of type 'id'
警告:语义问题:不兼容的整数到指针转换将“int”发送到“id”类型的参数
So, How do I set the value for an NSInteger.
那么,如何设置 NSInteger 的值。
Next Question, How do re-upload the array into core data? I fetch the array, make changes, and how do I apply those changes back to Core Data?
下一个问题,如何将数组重新上传到核心数据中?我获取数组,进行更改,以及如何将这些更改应用回 Core Data?
Thanks
谢谢
回答by isaac
Initialize an NSNumber (which is what CoreData is expecting) with your integer:
用你的整数初始化一个 NSNumber(这是 CoreData 所期望的):
NSNumber *marbleNumber = [NSNumber numberWithInt:marbles];
[records setObject:marbleNumber forKey@"marbles"];
Or:
或者:
[records setMarbles:[NSNumber numberWithInt:marbles]];
To persist your changes, you save your context:
要保留更改,请保存上下文:
NSError *error;
[myManagedObjectContext save:&error];
//handle your error
回答by Oscar Gomez
NSArrays will only take objects, so the first step is to turn your NSInteger into a NSNumber using this method:
NSArrays 只会接受对象,所以第一步是使用这个方法把你的 NSInteger 变成一个 NSNumber:
+ (NSNumber *)numberWithInt:(int)value
so:
所以:
NSNumber *myNumber = [NSNumber numberWithInt:marbles];
and then you can do:
然后你可以这样做:
[records setValue:myNumber forKey:@"marbles"];
Basically once you fetch the data, you get a managedObjectContext, think of it as a drawing board, and any changes (including adding or deleting new objects), you make to this objects may be saved again to CoreData using something like this:
基本上,一旦您获取数据,您就会获得一个 managedObjectContext,将其视为一个绘图板,并且您对该对象所做的任何更改(包括添加或删除新对象)都可以使用如下方式再次保存到 CoreData:
NSError *error;
if (![context save:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
Where context is the context you would get with your NSFetchedResultsController. Which you can get like this:
其中 context 是您将使用 NSFetchedResultsController 获得的上下文。你可以这样得到:
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
I would recommend taking a look at the Core Data programming guide
我建议看看核心数据编程指南
回答by Hugo the Lee
- (id)primitiveValueForKey:(NSString *)key;
- (void)setPrimitiveValue:(id)value forKey:(NSString *)key;
use NSNumber in place of (id)value
使用 NSNumber 代替 (id)value