在我的 View Controller 的主文件中,我为名为 finalStringsArray
的 NSArray 对象创建了一个属性:
@property (strong, nonatomic) NSArray *finalStringsArray;
然后在 viewDidLoad 中,我确保初始化对象:
self.finalStringsArray = [[NSArray alloc]init];
在 viewDidLoad 方法实现的下方,我向我的服务器查询数据,去除服务器发送给我的一些额外垃圾,例如空格,然后我将我的完美字符串放入我的 finalStringsArray
数组:
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSString *parseString = [[NSString alloc]initWithFormat:@"%@", objects];
NSString *cURL=[self stringBetweenString:@"=" andString:@")" withstring:parseString];
NSString *newString = [cURL stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *newString2 = [newString stringByReplacingOccurrencesOfString:@"(" withString:@""];
NSString *newString3 = [newString2 stringByReplacingOccurrencesOfString:@"\\n" withString:@""];
_finalStringsArray = [newString3 componentsSeparatedByString:@","];
int index;
for(index = 0; index < _finalStringsArray.count; index++) {
NSString *string = [[NSString alloc]init];
string = _finalStringsArray[index];
NSLog(@"Count: %d", _finalStringsArray.count);
}
NSLog(@"Count: %d", _finalStringsArray.count);
} }
];}
上面代码中所有重要的是这条语句:_finalStringsArray = [newString3 componentsSeparatedByString:@","];
这会将我的最终字符串添加到我的 _finalStringsArray
数组对象中。您会注意到我正在 NSLogging 数组的计数属性:NSLog(@"Count: %d", _finalStringsArray.count);
当我执行这些 NSLog 时,它们总是 NSLog 的正确计数为 2。
不过这是我的问题。再往下,我有一个方法实现也需要使用 _finalStringsArray
的 count 属性。但出于某种原因,它总是 NSLogs 为“0”,我不明白为什么。
下面是我的 viewDidLoad 下面的 3 个方法实现。我需要能够在方法实现中访问 _finalStringsArray
的计数属性
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
:
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
NSLog(@"all good string count3: %d", _finalParseStrings.count);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1 ;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"all good string count5: %d", [self.finalStringsArray count]);
return [self.finalStringsArray count];
}
最佳答案
findObjectsInBackgroundWithBlock:
是一种异步 方法。大概
numberOfRowsInSection:
在调用完成 block 之前被调用
并分配了一个新数组。
你可能应该在完成结束时调用[self.tableView reloadData]
block 以使用获取的数据更新 TableView 。
我不知道 PFQuery
是否在主线程上调用了完成 block 。
如果不是,那么您必须将数据源分配和 reloadData
调用分派(dispatch)到主队列。
关于ios - 全局变量不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125795/