使用NSPredicate过滤后更新原始NSMutableArray

时间:2011-11-13 12:57:17

标签: iphone ios nsarray nspredicate

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

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

现在,当用户启动同步操作时我:

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

到目前为止一切顺利。

现在我的(当前)问题 - >收到新数据(JSON req)后,我希望更新数组中这个'某个'对象的时间戳(并将其写入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 后,我想用过滤后的数据中的数据更新主阵列。

换句话说,我需要使用新的'timestamp'(对象字段)从Array更新对象。

我可以在更改filterd数组之后使用类似[stampArr addObject:[filteredStampArr copy]]的内容,但这只会创建信息的副本。我希望覆盖原始对象。

不知怎的(我想)我需要一个'指针'告诉我原始数组中数据的位置,以便我可以直接在主数组中更改数据?

(我希望我的问题很明确 - 如果不是,请说出来)

3 个答案:

答案 0 :(得分:2)

获取该项目,在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];

答案 1 :(得分:0)

当你获得filteredArray时,你可以直接更新其中的对象(而不是替换),并且可以在主数组中进行更新。

答案 2 :(得分:0)

仔细阅读API!

尝试:


[stampArr  filterUsingPredicate:];
相关问题