gpt4 book ai didi

iphone - 使用 NSPredicate 过滤后更新原始 NSMutableArray

转载 作者:行者123 更新时间:2023-11-29 11:19:03 25 4
gpt4 key购买 nike

我最近开始为 iOS 平台编程,但现在我需要一些帮助来弄清楚如何做“某事”:

  • 对于我的应用程序,我获取了一些 JSON 数据并将这些数据作为对象放入数组中
  • 这个数组被写入我自己的 PLIST 文件(在 docs 目录中)

现在,当用户开始同步操作时,我:

  • 从 PLIST 中获取数据
  • 获取来自 PLIST 的数组中某个对象的时间戳
  • 在新的 JSON 请求中使用时间戳(用于新数据)

到目前为止一切顺利。

现在针对我的(当前)问题 -> 在收到新数据(JSON 请求)后,我希望更新数组中这个“特定”对象的时间戳(并将其写入 Plist)。

使用 NSPredicate 我能够在主数组 (stampArr) 中找到正确的数据集。

NSString *documentsDir = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
NSString *plistPath = [documentsDir stringByAppendingPathComponent:@"stamps.plist"];

NSMutableArray *stampArr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];

NSPredicate *filter = [NSPredicate predicateWithFormat:@"eventid = 1"];
NSMutableArray *filteredStampArr = [stampArr filteredArrayUsingPredicate:filter];

但是现在,在更新 filteredStampArr 之后,我想用过滤后的数组中的数据更新主数组。

换句话说,我需要使用新的“时间戳”(对象字段)更新数组中的对象。

我当然可以在更改 filterd 数组后使用 [stampArr addObject: [filteredStampArr copy]] 之类的东西,但这只会创建信息的副本。我想覆盖原来的对象。

不知何故(我认为)我需要一个“指针”来告诉我数据在原始数组中的位置,以便我可以直接在主数组中更改数据?

(我希望我的问题很清楚——如果不清楚请说)

最佳答案

获取项目,在 stampArr 中找到它的索引并将其替换为 newItem

NSArray *filteredStampArr = [stampArr filteredArrayUsingPredicate:filter];
id item = [filteredStampArr objectAtIndex:0]; // id because the type of the item is not known

NSUInteger itemIndex = [stampArr indexOfObject:item];

[stampArr replaceObjectAtIndex:itemIndex withObject:newItem];

关于iphone - 使用 NSPredicate 过滤后更新原始 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8111667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com