0

以下是实体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本质上是一个NSMutableArraywithNSNumber元素。在一个函数中,我正在更新这个数组:

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

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

4

2 回答 2

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!) }
于 2013-10-19T10:08:59.803 回答
0

刚刚解决了。为了更新核心数据实体中的数组属性,必须将该数组分配给@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)
    {
         ...
    }
}
于 2013-10-19T21:54:12.500 回答