具有数组属性的核心数据

时间:2013-10-19 09:46:31

标签: ios objective-c core-data

以下是实体Player头文件。

@interface Player : NSManagedObject

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

@end

@interface items : NSValueTransformer
@end

items基本上是NSMutableArrayNSNumber元素。在一个函数中,我正在更新这个数组:

- (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函数中。

- (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)
    {
        ...
    }
}

问题是只要我没有关闭任务栏中的应用程序,就可以在其他视图中看到更新。有什么问题?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

核心数据可以存储数组,但您必须使用“可转换”属性。一般来说,它不是很好的设计。一个简单的解决方案是将您的数字数组转换为可以存储的数据。例如,在许多情况下,仅使用字符串就足够了。

编码:

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

解码:

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!) }

答案 1 :(得分:0)

刚刚解决了。为了更新Core Data实体内的数组属性,必须将该数组分配给视图控制器类中的另一个@property数组,并更新@property数组。在更新数据库之前,必须将@property数组分配回实体属性。

// to hold the player items
// _player.items cannot be directly updated
@property (strong, nonatomic) NSMutableArray* items;

- (void)viewDidLoad
{
    [super viewDidLoad];
    ...
    NSError* err = nil;
    NSMutableArray* results = [[_moc executeFetchRequest:fr error:&err] mutableCopy];
    if (err || results.count == 0)
    {
        ...
    } else
    {
        _player = [results objectAtIndex:0];
        _items = _player.items;
    }
}

// events
- (void)itemWasDropped:(ItemIndex)item
{
    // the current number of this item
    int nNum = [[_items objectAtIndex:item] intValue];
    // to increment the number
    [_items replaceObjectAtIndex:item withObject:[NSNumber numberWithInt:nNum + 1]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // to update the database
    _player.items = _items;
    NSError* err = nil;
    BOOL bSucc = [_moc save:&err];
    if (err || !bSucc)
    {
         ...
    }
}