【发布时间】:2012-08-14 17:09:26
【问题描述】:
我正在尝试替换可变数组中的字典。 第 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' 的整数到指针转换不兼容;用 & 获取地址
2:指向整数转换的不兼容指针将“int *”发送到 NSUInteger'(又名“unsigned int”)类型的参数
【问题讨论】:
-
if(int i=0;i<[tmpMutArr count];i++)应该是for循环?你是如何通过编译器得到的? - 请尽量缩进源代码。 -
我知道这不能正常工作,我使用一些示例代码将其组合在一起,这就是为什么我需要一些帮助才能使其正确,因为这已经超出了我的经验水平。 'i' 甚至没有被声明。但我想我应该是某种“for”循环,是的。
-
字面意思就是用“for”替换“if”
-
int *index应该是int index。
标签: objective-c cocoa