我的问题是我有NSMutableArray
,其名称为latLongArray
,如果数组计数大于4,则包含对象。
我想在另一个Array中添加名称为elementArray的每个第4个对象,如果少于4个想要在elementArray中添加所有对象而不是在NSLog中打印所有数据
任何人都可以帮助我这是我对iPhone开发的新手。 这是我的代码
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
placeDC *placedc;
placedc = [dataArray objectAtIndex:[indexPath row]];
if ([txtFrom isFirstResponder]) {
txtFrom.text=cellText;
NSLog(@"%@",cellText);
originlat=placedc.latitude;
originlng=placedc.longitude;
NSLog(@"%@",placedc.countryFullName);
}
else
{
txtTo.text=cellText;
destinationLat=placedc.latitude;
DestinationLng=placedc.longitude;
DBHandler *db=[[DBHandler alloc]init];
NSLog(@"%@",placedc.countryFullName);
latLongArray=[db googlePlaces:originlat :originlng :destinationLat :DestinationLng];
if ([latLongArray count]>4) {
for (int i =0; i<=[latLongArray count]; i=i+4) {
}
NSLog(@"%d",[elentArray count]);
}
}
myTableView.hidden=YES;
[self.view endEditing:YES];
}
答案 0 :(得分:3)
只需改变:
NSMutableArray *newArrayOfFourthElement = [[NSMutableArray alloc] init];
elementArray = [[NSMutableArray alloc] init];
int j = 3;
if ([latLongArray count]>4)
{
for (int i =0; i <= [latLongArray count]; i=i+4)
{
if (j < [latLongArray count])
{
[newArrayOfFourthElement addObject:[latLongArray objectAtIndex:j]]; // This line will add all the forth element(i.e. 4,8,12....) from your latLongArray to newArrayOfFourthElement array.
}
j = j + 4;
}
}
else
{
elementArray = [[NSMutableArray alloc]initWithArray:latLongArray];
}
NSLog("New array is %@",newArrayOfFourthElement);
NSLog("elementArray is %@",elementArray);
答案 1 :(得分:0)
-(void) arrayExample{
NSMutableArray *newArray = [[NSMutableArray alloc] init];
if (_longArray.count > 4) {
int lastObjectIndex = _longArray.count -1;
int nextIndexToAd = 3;
while (nextIndexToAd <= lastObjectIndex) {
[newArray addObject:[_longArray objectAtIndex:nextIndexToAd]];
nextIndexToAd += 4;
}
}
else{
newArray = [_longArray mutableCopy];
}
}
答案 2 :(得分:0)
如果您想添加第四个元素
NSMutableArray *elementArray = [[NSMutableArray alloc] init];
if ([latLongArray count]>4)
{
//add 4th element mean object at index 3
[elementArray addObject:[latLongArray objectAtIndex:3]];
}
else{
elementArray=[latLongArray mutableCopy];
}
NSLog(@"elentArray array >> %@ and count = %d",elentArray,[elentArray count]);
如果你想添加每个第四个元素
NSMutableArray *latLongArray = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];
NSMutableArray *elementArray = [[NSMutableArray alloc] init];
if ([latLongArray count]<4)
{
elementArray=[latLongArray mutableCopy];
}
else{
do {
[elementArray addObject:[latLongArray objectAtIndex:3]];
[latLongArray removeObjectsInRange:(NSRange){0, 4}];
} while ([latLongArray count]>4);
}
NSLog(@"%@",elementArray);