获取数组对象的索引

时间:2012-08-14 02:55:43

标签: iphone objective-c ios xcode

这是我要完成的代码

-(IBAction)theButtonIsSelected:(id)sender {

    NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
    [mutDict setObject:@"Yes" forKey:@"Favorite"];

    NSString *nameString = [mutDict valueForKey:@"Name"];

    NSArray *allObjects;
    allObjects = [[NSArray alloc] initWithContentsOfFile:path];

    NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjects];
    int index;
     //I think I just need a little piece right here to set the current allObjectsIndex to match nameString?
    [tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];

    allObjects = nil;
    allObjects = [[NSArray alloc] initWithArray:tmpMutArr];

    [allObjects writeToFile:path atomically:YES];
    }

这是我的问题:

if (what I'm trying to do above can be done) {
How to finish it?
} else {
How to make a function to change the "Favorite" key's value of plist object, 
when detailsDataSource not always containing the complete list of objects?
That's why I'm trying to include allObjects and index in this code.
}

编辑:

代码现在看起来像这样:

     NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
     [mutDict setObject:@"Yes" forKey:@"Favorite"];

     NSString *nameString = [[detailsDataSource objectAtIndex:detailIndex] valueForKey:@"Name"];

     NSArray *allObjectsArray = [[NSArray alloc] initWithContentsOfFile:path];

     NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];


     if(int i=0;i<[tmpMutArr count];i++)
//Errors ^here              and here^
     {
     if([[tmpMutArr  objectAtIndex:i] isKindOfClass:[NSDictionary class]])
     {
     NSMutableDictionary *tempDict = [tmpMutArr  objectAtIndex:i];
     if([tempDict valueForKey:@"Name" == [NSString stringWithFormat:@"@%", nameString];) //Is this correct?
     {
     index = i; //index of dictionary
     }
     }
     }

     [tmpMutArr replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithDictionary:mutDict]];

     allObjectsArray = nil;
     allObjectsArray = [[NSArray alloc] initWithArray:tmpMutArr];

     [allObjectsArray writeToFile:path atomically:YES];

错误:1预期表达式2未声明的标识符'i'如何声明我并修复其他错误?

1 个答案:

答案 0 :(得分:3)

你可以像这样获得字典索引:

 if(int i=0;i<[tmpMutArr count];i++)
 {
   if([[tmpMutArr  objectAtIndex:i] isKindOfClass:[NSDictionary class]])
   {
      NSMutableDictionary *tempDict = [tmpMutArr  objectAtIndex:i];
      if([tempDict objectForKey:@"Favorite")
      {
         index = i; // here u have your index of dictionary
      }
   }
 }