我正在尝试替换可变数组中的字典。 步骤1到4应该是好的,但是我在步骤5 - 6中遇到了一些麻烦。你能否告诉我要使这个功能发挥作用需要做些什么:
- (void) updatePlist {
// 1: String with plist path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory
stringByAppendingPathComponent:@"Object.plist"];
// 2: Create a mutable dictionary containing current object and write
// "Yes" to the "Favorite" string:
NSMutableDictionary *mutDict = [NSMutableDictionary
dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:@"Yes" forKey:@"Favorite"];
// 3: Make a string containing current object name:
NSString *nameString = [[detailsDataSource objectAtIndex:detailIndex]
valueForKey:@"Name"];
// 4: Make a mutable array containing all objects:
NSArray *allObjectsArray = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
// 5: Search for the dictionary in tmpMutArr with "Name" value matching nameString:
int *index;
for(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:@"Name"] isEqualToString:[NSString
stringWithFormat:@"%@", nameString]])nameString];)
{
index = i;
}
}
}
// 6: Replace the old dictionary with the new one and write array to plist:
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
allObjectsArray = nil;
allObjectsArray = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjectsArray writeToFile:path atomically:YES];
}
编辑:
现在的问题是:
for(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:@"Name"] isEqualToString:
[NSString stringWithFormat:@"%@", nameString]])nameString];)
{
index = i; // Here 1
}
}
}
// ---------------------------- v And here 2
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
1:不兼容的整数到指针转换从'int'分配给'int';用&amp;
取得地址2:指向整数转换的不兼容指针将'int *'发送到NSUInteger类型的参数'(又名'unsigned int')
答案 0 :(得分:2)
替换行:
if([tempDict valueForKey:@"Name" == [NSString stringWithFormat:@"", nameString];)
这一行:
if([[tempDict valueForKey:@"Name"] isEqualToString: [NSString stringWithFormat:@"%@", nameString]])
因为你在这里使用字符串比较。
答案 1 :(得分:0)
正如Martin R的评论中所指出的,您正在尝试将int值保存到int指针变量中。
int index; //instead of 'int *index;'
这种改变应该可以解决问题。
如果您编写了int *index;
然后index = &i;
,那可能会有效,因为您正在以这种方式保存指向整数的指针。但它似乎并不是你想要做的。
第二个错误是由于您为此方法提供了int指针而不是整数:
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
但是将索引声明为整数可以解决这两个错误。