具有数组属性的核心数据 [英] Core Data with Array Attribute

查看:136
本文介绍了具有数组属性的核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是实体 Player 头文件。

@interface Player : NSManagedObject

@property (nonatomic, retain) NSNumber * experience;
@property (nonatomic, retain) id items;
@property (nonatomic, retain) NSNumber * level;

@end

@interface items : NSValueTransformer
@end

项本质上是 NSMutableArray NSNumber 元素。在一个函数中,我更新这个数组:

items is essentially an NSMutableArray with NSNumber elements. And inside one function, I'm updating this array:

- (void)itemWasDropped:(ItemIndex)item
{ // _player has been correctly retrieved from the database
    // the current number of this item
    int nNum = [[_player.items objectAtIndex:item] intValue];
    // to increment the number
    [_player.items replaceObjectAtIndex:item withObject:[NSNumber numberWithInt:nNum + 1]];
}

此函数完全调用。我保存在 viewWillDisappear 函数中的上下文。

This function gets called perfectly. I save the context in the viewWillDisappear function.

- (void)viewWillDisappear:(BOOL)animated
{ // _moc is an NSManagedObjectContext instance that has been correctly initialised.
    // to update the database
    NSError* err = nil;
    BOOL bSucc = [_moc save:&err];
    if (err || !bSucc)
    {
        ...
    }
}

问题是,只要我不在任务栏中关闭应用程序,更新就在其他视图中可见。有什么问题?任何人都可以帮助?

The problem is that the updates are visible in other views as long as I do not shut down the app in the task bar. What's the problem? Anyone can help?

推荐答案

核心数据可以存储数组,但是必须使用可变换属性。一般来说这不是很好的设计。一个简单的解决方案是将你的数字数组转换成可以存储的东西。例如,在许多情况下,只需使用字符串就足够了。

Core data can store arrays, but you will have to use a "transformable" attribute. In general it is not very good design. One easy solution is to transform your numbers array into something that can be stored. For example, in many cases it is sufficient to just use a string.

编码:

player.items = [numbers componentsJoinedByString:@","];
// Swift
player.items = numbers.joinWithSeparator(",")

Decode:

NSMutableArray* numbers = [NSMutableArray array];
for (NSString *s in [player.items componentsSeparatedByString:@","]) {
  [numbers addObject:@([s integerValue])];
}
// Swift
let numbers = player.items.characters.split { $0 == "," } .map { Int($0!) }

这篇关于具有数组属性的核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆