iOS中的范围和线程(Scope and threading in iOS)
我对iOS中的Web服务调用和线程都不熟悉。 我的应用程序中有一个包含tableview控件的
ViewController
。 我使用通过JSON Web服务获得的数据填充表。 JSON Web服务在其自己的线程上调用,在此期间我填充了NSArray
和NSDictionary
。我的数组和字典似乎超出了范围,因为我的
NSLog
语句为数组计数返回零,即使在fetchedData
中数组已完全填充。有人可以解释为什么我的数组和字典对象在线程外是空的吗?
- (void)viewDidLoad { [super viewDidLoad]; NSString *serviceEndpoint = [NSString stringWithFormat: @"http://10.0.1.12:8888/platform/services/_login.php?un=%@&pw=%@&ref=%@", [self incomingUsername], [self incomingPassword], @"cons"]; NSURL *url = [NSURL URLWithString:serviceEndpoint]; dispatch_async(kBgAdsQueue, ^{ NSData *data = [NSData dataWithContentsOfURL:url]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); NSLog(@"ARRAY COUNT: %d\n", [jsonArray count]); } -(void)fetchedData:(NSData*)responseData{ NSError *error; jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; jsonArray = [[jsonDict allKeys]sortedArrayUsingSelector:@selector(compare:)]; for(NSString *s in jsonArray){ NSLog(@"%@ = %@\n", s, [jsonDict objectForKey:s]); } }
I am kind of new to web service calls and threading in iOS. I have a
ViewController
in my app that contains a tableview control. I am populating the table with data obtained via a JSON web service. The JSON web service is called on its own thread, during which I am populating anNSArray
andNSDictionary
.My array and dictionary seem like they are going out of scope since my
NSLog
statement is returning zero for the array count even though while infetchedData
the array is fully populated.Can someone offer an explanation as to why my array and dictionary objects are empty outside of the thread?
- (void)viewDidLoad { [super viewDidLoad]; NSString *serviceEndpoint = [NSString stringWithFormat: @"http://10.0.1.12:8888/platform/services/_login.php?un=%@&pw=%@&ref=%@", [self incomingUsername], [self incomingPassword], @"cons"]; NSURL *url = [NSURL URLWithString:serviceEndpoint]; dispatch_async(kBgAdsQueue, ^{ NSData *data = [NSData dataWithContentsOfURL:url]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); NSLog(@"ARRAY COUNT: %d\n", [jsonArray count]); } -(void)fetchedData:(NSData*)responseData{ NSError *error; jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; jsonArray = [[jsonDict allKeys]sortedArrayUsingSelector:@selector(compare:)]; for(NSString *s in jsonArray){ NSLog(@"%@ = %@\n", s, [jsonDict objectForKey:s]); } }
原文:https://stackoverflow.com/questions/16170779
最满意答案
哇,真是个噩梦。 我找到了罪魁祸首。
我创建了一个
TypeConverter
来将List<Integer>
转换为字符串(并返回),以便它可以存储在房间DB中的单个列中,而无需修改现有的DTO。 但是,当我切换到使用Long
类型作为ID时,我无法在转换器中转换下面的单个泛型参数; 仔细查看以下代码:public class IdsListConverter { @TypeConverter public List<Long> idsFromString(String value) { Gson gson = new Gson(); if (value == null || value.isEmpty()) { return null; } else { Type resultType = new TypeToken<List<Integer>>(){}.getType(); return gson.fromJson(value, resultType); } } @TypeConverter public String idsToString(List<Long> ids) { if (ids == null) { return null; } else { Gson gson = new Gson(); return gson.toJson(ids); } } }
Wow, what a nightmare. I have found the culprit.
I had created a
TypeConverter
to turn aList<Integer>
to into a string (and back) so that it can be stored in a single column in the DB in room without having to modify the existing DTOs. However, when I switched over to usingLong
types as IDs, I failed to convert a single generic argument below in the converter; look carefully at the following code:public class IdsListConverter { @TypeConverter public List<Long> idsFromString(String value) { Gson gson = new Gson(); if (value == null || value.isEmpty()) { return null; } else { Type resultType = new TypeToken<List<Integer>>(){}.getType(); return gson.fromJson(value, resultType); } } @TypeConverter public String idsToString(List<Long> ids) { if (ids == null) { return null; } else { Gson gson = new Gson(); return gson.toJson(ids); } } }
相关问答
更多-
d={} new_list = [d[i] for i in values if d.setdefault(i,len(d)+1)] d={} new_list = [d[i] for i in values if d.setdefault(i,len(d)+1)]
-
不,没有这样的内置功能。 这是一个天真的实现: let mode = function | [] -> None | xs -> let mostFrequentTwo = xs |> Seq.groupBy id |> Seq.map (fun (n, ns) -> n, Seq.length ns) |> Seq.sortByDescending snd ...
-
如何乘以整数列表的文本列表并获得一长串文本?(How to multiply a list of text by a list of integers and get one long list of text?)[2021-12-24]
你很亲密! 您需要做的就是使用list.extend而不是list.append : new_list = [] for i in zip(lista, listb): new_list.extend([i[0]] * i[1]) 这将使用您提供的元素(附加每个单独元素)扩展list new_list ,而不是附加完整列表。 如果您需要获得幻想,您可以始终使用itertools函数来实现相同的效果: from itertools import chain, repeat new_list = l ... -
2长整数的LCM(LCM of 2 long long integers)[2023-06-16]
你总是会遇到溢出问题,特别是当你有大量的互质数字时。 但是要稍微抵消这一点,你可以像迈克尔建议的那样写a * (b/gcd(a,b)) 。 由于gcd(a,b)是a和b的除数,因此不必担心由于整数除法导致的不准确结果。 You're always going to have overflow problems, especially whenever you have large coprime numbers. But to offset this a little, you can do as Mich ... -
约束列表只采用整数(constraint list to take only integers)[2022-12-24]
通过继承collections.MutableSequence而不是list你可以减少代码。 MutableSequence将根据以下五种方法自动实现所有其他列表方法。 from collections import MutableSequence class IntList(MutableSequence): def __init__(self): super(IntList, self).__init__() self._list = [] def _ ... -
数据绑定列表整数(Databind List of Integers)[2022-05-20]
这应该工作: <%# Container.DataItem %> This should work: <%# Container.DataItem %> -
哇,真是个噩梦。 我找到了罪魁祸首。 我创建了一个TypeConverter来将List
转换为字符串(并返回),以便它可以存储在房间DB中的单个列中,而无需修改现有的DTO。 但是,当我切换到使用Long类型作为ID时,我无法在转换器中转换下面的单个泛型参数; 仔细查看以下代码: public class IdsListConverter { @TypeConverter public List idsFromString(String value) { ... -
在求和时将元素转换为Long(或BigInt应该那么远): x.view.map(_.toLong).sum 您也可以返回折叠 x.foldLeft(0L)(_ + _) (注意:如果你总结一个范围,也许最好做一点数学,但我明白这不是你事实上的做法) Convert the elements to Long (or BigInt should that go that far) while summing: x.view.map(_.toLong).sum You can also go back t ...
-
添加到列表中的整数(Add to integers in a list)[2023-05-05]
这是一个例子,其中添加的东西来自字典 >>> L = [0, 0, 0, 0] >>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1}) >>> for item in things_to_add: ... L[item['idx']] += item['amount'] ... >>> L [0, 1, 1, 0] 以下是从另一个列表添加元素的示例 >>> L = [0, 0, 0, 0] >>> things_ ... -
排序整数(Sorting integers)[2022-07-28]
你已经重新发现了维基百科所谓的计数排序 ,这是一种非常简单的分布排序算法。 它是您的数据集的最佳算法:它在O(N + k)时间内运行(N是记录数,k是不同键的数量),使用O(k)附加存储,并且具有非常低的系数。 You've rediscovered what Wikipedia calls counting sort, a very simple distribution sorting algorithm. It is the optimal algorithm for your data set: i ...