NSNumber numberWithInt:返回奇怪的数字?
我刚刚开始使用核心数据,遇到了一个问题,我需要使用适当的 ID 保存新对象。
我试图添加行中的下一个数字作为用户添加的对象的 ID:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorites" inManagedObjectContext:managedObjectContext]];
[request setIncludesSubentities:NO];
NSError *err;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&err];
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[NSNumber numberWithInt:count] forKey:@"favoritesID"];
如果我然后去获取 valueForKey:@"favoriteID" 我会得到类似“81933072”的内容,这是错误的。
我检查了 count
,它是正确的数字,只是当我将它放入 Core Data 时,它变成了其他东西。顺便说一句,favoriteID
是一个 int16。
I am just starting out with Core Data and ran into an issue where I need to save the new object with the appropriate ID.
I'm trying to add the next number in the row as an ID for the object the user adds:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorites" inManagedObjectContext:managedObjectContext]];
[request setIncludesSubentities:NO];
NSError *err;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&err];
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[NSNumber numberWithInt:count] forKey:@"favoritesID"];
If I then go and get the valueForKey:@"favoriteID" I get something like "81933072", which is wrong.
I have checked count
and it's the correct number, it's just when I put it into Core Data that it becomes something else. favoriteID
is an int16 btw.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
valueForKey:将返回 NSNumber,而不是整数。您需要对其调用
[myNumber integerValue]
。编辑:那么您要将 NSNumber 分配给 int16 吗?那是行不通的。您应该更改变量类型。
valueForKey: will return the NSNumber, not an integer. You need to call
[myNumber integerValue]
on it.Edit: So you're assigning an NSNumber to an int16? That's not gonna work. You should change your variable type.