从数组中调用元素并将其分配给变量?

Calling an element from an array and assigning it to a variable?

有人可以告诉我如何从数组中调用元素并将其分配给变量吗?

在我的 viewdidload 中,我创建了一个随机数组。

- (void)viewDidLoad {
    int n = 40;
    NSMutableArray *numbers = [NSMutableArray array];
    for (int i = 1; i <= n; i++) {
        [numbers addObject:[NSNumber numberWithInt:i]];
    }
    NSMutableArray *result = [NSMutableArray array];
    while ([numbers count] > 0) {
        int r = arc4random() % [numbers count];
        NSNumber *randomElement = [numbers objectAtIndex:r];
        [result addObject:randomElement];
        [numbers removeObjectAtIndex:r];
    }
    NSLog(@"%@", result);
    NSLog (@"The 4th integer is: %@", [result objectAtIndex:3]);
}

在另一节中,我想调用这些值。 例如

-(void)nextpiece{
    countnumber=2;
    count=[result objectAtIndex:countnumber];
}

countnumber 和 count 是整数。问题是它无法识别结果数组。错误是 "Use of undeclared identifier 'result'" 有人可以提供解决方案吗?非常感谢

问题是因为 resultviewDidLoad 内部的局部变量,您只能在 viewDidLoad 内部使用它。如果你想要一个可以在 viewDidLoadnextpiece 中使用的变量。我建议将 result 作为 class 的 属性。

例如

@interface YourViewController ()

@property (nonatomic, strong) NSMutableArray* result;

@end

@implementation YourViewController

- (void)viewDidLoad {
  int n = 40;
  NSMutableArray *numbers = [NSMutableArray array];
  for (int i = 1; i <= n; i++) {
    [numbers addObject:[NSNumber numberWithInt:i]];
  }
  _result = [NSMutableArray array];
  while ([numbers count] > 0) {
    int r = arc4random() % [numbers count];
    NSNumber *randomElement = [numbers objectAtIndex:r];
    [_result addObject:randomElement];
    [numbers removeObjectAtIndex:r];
  }
  NSLog(@"%@", _result);
  NSLog (@"The 4th integer is: %@", [_result objectAtIndex:3]);
}

-(void)nextpiece{
  int countnumber = 2;
  NSNumber *count = [_result objectAtIndex:countnumber];
}

@end